2017-10-11 4 views
3

List counties에는 고유 한 카운티 이름 만 있고 List txcArray에는 해당 도시의 도시 이름, 카운티 이름 및 인구수가 포함되어 있습니다.자바 8에서 람다 식으로 여러 스트림 및 .map 함수를 사용하는 방법

각 카운티의 가장 큰 도시 이름을 txcArray에서 람다식이있는 Java 8과 Stream을 사용하여 가져와야합니다.

List<String> largest_city_name = 
    counties.stream() 
      .map(a -> txcArray.stream() 
           .filter(b -> b.getCounty().equals(a)) 
           .mapToInt(c -> c.getPopulation()) 
           .max()) 
      .collect(Collectors.toList()); 

나는 가장 큰 인구와 City의 이름을 가져 .max() 후 다른 .MAP 문을 추가하려고하지만 내 새로운 람다 식이 존재하지 않습니다 여기에

내가 지금까지 가지고있는 코드입니다 txcArray 스트림에서는 int 유형 및 texasCitiesClass 유형으로 만 인식합니다. 여기 내가하려는 일이 있습니다.

List<String> largest_city_name = 
    counties.stream() 
      .map(a -> txcArray.stream() 
           .filter(b -> b.getCounty().equals(a)) 
           .mapToInt(c->c.getPopulation()) 
           .max() 
           .map(d->d.getName())) 
      .collect(Collectors.toList()); 

누군가 내가 뭘 잘못하고 있다고 말할 수 있습니까?

답변

5

. txcArray 및 군별로 그룹화 :

Collection<String> largestCityNames = txcArray.stream() 
     .collect(Collectors.groupingBy(
       City::getCounty, 
       Collectors.collectingAndThen(
         Collectors.maxBy(City::getPopulation), 
         o -> o.get().getName()))) 
     .values(); 
+0

니스. 나는 그것에 대해 생각하지 않았다. 훨씬 더 간단합니다. +1 – Eran

+0

원래의 의도는 가장 큰 도시 이름 목록이 같은 순서로 카운티 목록이라는 것입니다. 여기에 도시 이름의 순서가없는 컬렉션이 아닌'Map'을 유지하는 것이 더 나을 것입니다 ... – Holger

2

음, 한 번 mapIntStream에 도시의 Stream에, 당신은 int 값으로 해당 도시의 이름을 복구 할 방법이 없습니다.

사용 Streammax 대신 IntStream로 변환 :

List<String> largest_city_name = 
    counties.stream() 
      .map(a -> txcArray.stream() 
           .filter(b -> b.getCounty().equals(a)) 
           .max(Comparator.comparingInt(City::getPopulation)) 
           .get()) 
      .map(City::getName) 
      .collect(Collectors.toList()); 

map 작업이 가장 높은 인구의 City 각 군 매핑이 방법. maxOptional<City>을 반환하므로 Optional이 비어 있습니다 (즉, 일부 카운티에는 도시가 없음). get()은 예외를 throw합니다.

그 문제를 방지하려면, 당신은 쓸 수 있습니다 :

List<String> largest_city_name = 
    counties.stream() 
      .map(a -> txcArray.stream() 
           .filter(b -> b.getCounty().equals(a)) 
           .max(Comparator.comparingInt(City::getPopulation)) 
           .map(City::getName) 
           .orElse("")) 
      .collect(Collectors.toList()); 

이 빈 String에 어떤 도시가없는 군을 매핑합니다.

이 코드는 txcArrayCityList<City>입니다 가정

클래스 도시 { 공공 문자열 getName() {반환 남;} 공공 INT의 getPopulation() {반환 팝} 공공 문자열 getCounty을 () {return cnt;} 문자열 이름; int pop; 문자열 cnt; public City (String nam, int pop, String cnt) { this.nam = nam; this.pop = pop; this.cnt = cnt; } }

countiesList<String>이다. 내 가정이 정확하지 않은 경우 조정을해야합니다.

이제 다음 List들과 코드를 테스트 :

List<String> counties=new ArrayList<>(); 
counties.add ("First"); 
counties.add ("Second"); 
counties.add ("Third"); 
counties.add ("Fourth"); 
List<City> txcArray = new ArrayList<>(); 
txcArray.add (new City("One",15000,"First")); 
txcArray.add (new City("Two",12000,"First")); 
txcArray.add (new City("Three",150000,"Second")); 
txcArray.add (new City("Four",14000,"Second")); 
txcArray.add (new City("Five",615000,"Third")); 
txcArray.add (new City("Six",25000,"Third")); 

이 출력을 List을 생산 : 당신은 전부 counties 목록이 필요하지 않습니다

[One, Three, Five, ] 
+0

내가 잘못 입력 한 변수 이름을 통해 도움을 주셔서 감사합니다. –

+0

@Octaviogarcia 환영합니다! – Eran