본문 바로가기

Programming!

Java 8 Collection 돌려보기

우선 City라는 Dto를 하나 만들어 둔다.

public class City {

    

    private Long id;

    

    private String name;

    

    private String country;

    

    public City(Long id, String name, String country) {

        this.id = id;

        this.name = name;

        this.country = country;

    }


...getter/setter...

}



해당 City를 List로 만든 후, 여러가지를 해볼 수 있다. 

가령 cities의 특정 property를 키로 두고 List<City>를 가지는 맵을 만든다던지 하는.. 예제를 직접 만들어 보자.


public class CollectionExample {


    private static List<City> getCities(){

        List<City> cities = new ArrayList<>();

        cities.add(new City(1L, "서울", "대한민국"));

        cities.add(new City(2L, "대구", "대한민국"));

        cities.add(new City(3L, "Newyork", "미국"));

        cities.add(new City(4L, "경기도", "대한민국"));

        cities.add(new City(5L, "대전", "대한민국"));

        cities.add(new City(6L, "LA", "미국"));

        return cities;

    }


    public static void main(String[] args){

        // Key 는 CityName이 되며, City Object를 Value로 가지는 Map을 만든다.

        Map<String, City> example1 = getCities().stream().collect(Collectors.toMap(City::getName, Function.identity()));

        

        // Key 는 Country가 되며, List<City>를 Value로 가지는 Map을 만든다.

        Map<String, List<City>> example2 = getCities().stream().collect(Collectors.groupingBy(City::getCountry, Collectors.toList()));

        

        // Key 는 Country가 되며, List<String:CityName>를 Value로 가지는 Map을 만든다.

        Map<String, List<String>> example3 = getCities().stream().collect(Collectors.groupingBy(City::getCountry, Collectors.mapping(City::getName, Collectors.toList())));

    }

}


위와 같은 예제를 좀 더 확장할 수 있을것이다. 가령 미국을 뺀 '대한민국'만으로 구성한다던지..

Map<String, List<City>> example2_2 = getCities().stream().filter(o -> !"미국".equals(o.getCountry())).collect(Collectors.groupingBy(City::getCountry, Collectors.toList()));

주) .filter 내의 "o -> !"미국".equals(o.getCountry())" 이런 부분은 별도의 Function으로 빼도 좋다.


음.. 전체적으로 Collection을 람다 형식으로 사용하고는 있지만, 계속 써보고 분석해봐야지만 늘어나는거 같다. 간혹 나도모르게 for 를 돌리는 경우가 많아서.