2017-10-11 41 views
3

我有一个List counties,它只包含唯一的县名,而List txcArray包含该城市的城市名称,县名和人口。如何在lambda表达式中使用java 8中的多个流和.map函数

我需要从txcArray获得每个县的最大城市名称,只使用Java 8的lambda表达式和Stream s。

这里是我的代码至今:

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()); 

我想.max()后添加另一个.MAP语句来获得City人口最多的名字,但我的新lambda表达式不存在从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

你不完全需要counties列表。仅仅通过县流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

那么,一旦到map城市StreamIntStream,有没有办法让你恢复与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最高的人群。请注意,max返回一个Optional<City>,所以它Optional是空的(即一些县没有城市),get()会抛出异常。

为了避免这个问题,你可以写:

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

此代码假定txcArrayList<City>,其中City是:

级市{ 公共字符串的getName(){返回越南;} 公众诠释getPopulation(){回报弹出;} 公共字符串getCounty( ){return cnt;} String nam; int pop; String cnt; public City(String nam,int pop,String cnt){this.nam = nam; this.pop = pop; this.cnt = cnt; } }

countiesList<String>。如果我的假设不准确,则必须进行一些调整。现在

,测试代码如下List S:

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

[One, Three, Five, ] 
+0

你是对的,我有错变量名称谢谢你帮助我通过它。 –

+0

@Octaviogarcia不客气! – Eran