如何在Java 8中通过另一个元素的元素对列表的元素进行分组 [英] How to group elements of a List by elements of another in Java 8

查看:539
本文介绍了如何在Java 8中通过另一个元素的元素对列表的元素进行分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下问题:给定这些类,

I have the following problem: Given these classes,

class Person {
    private String zip;
    ...
    public String getZip(){
        return zip;
    }
}

class Region {
    private List<String> zipCodes;
    ...
    public List<String> getZipCodes() {
        return zipCodes;
    }
}

a 根据 Region 是否包含地图< Person,List< Region>个人的邮政编码?换句话说,我如何使用邮政编码属于这些地区的人来分组区域?

using the Java 8 Stream API, how do I obtain a Map<Person, List<Region>> based on whether the Region contains that Person's zip code? In other words how do I group the regions by the people whose zip codes belong to those regions?

我在Java 7中使用了老式的方式,但现在我必须迁移代码以利用Java 8中的新功能。

I've done it in Java 7 the old fashioned way, but now I have to migrate the code to take advantage of the new features in Java 8.

谢谢你,

Impeto

推荐答案

我怀疑最简单的方法 - 我不太满意其他答案 -

I suspect the cleanest way to do this -- I'm not quite happy with the other answers posted -- would be

 persons.stream().collect(Collectors.toMap(
    person -> person,
    person -> regions.stream()
       .filter(region -> region.getZipCodes().contains(person.getZip()))
       .collect(Collectors.toList())));

这篇关于如何在Java 8中通过另一个元素的元素对列表的元素进行分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆