List:把List中的元素按照某一条件进行分组

郎家岭伯爵 2023年04月24日 307次浏览

背景

设想有一个 List,我们需要对 List 中的元素按照某一条件进行分组。

实现

首先我们创建一个包含多个元素的 List:

UserEntity userEntity = new UserEntity().setAge(20L).setPassword("123").setUserName("langjialing");
UserEntity userEntity1 = new UserEntity().setAge(20L).setPassword("456").setUserName("langjialing456");
UserEntity userEntity2 = new UserEntity().setAge(25L).setPassword("789").setUserName("langjialing789");
UserEntity userEntity3 = new UserEntity().setAge(25L).setPassword("123").setUserName("langjialing");

List<UserEntity> list = new ArrayList<>();
list.add(userEntity);
list.add(userEntity1);
list.add(userEntity2);
list.add(userEntity3);

接下来我们来按照“年龄”进行分组:

// 把list按年龄分组
Map<Long, List<UserEntity>> collect = list.stream().collect(Collectors.groupingBy(UserEntity::getAge));
log.info(collect.toString());

// 把list按年龄分组,然后把每个分组的用户名拼接起来
Map<Long, String> collect1 = list.stream().collect(Collectors.groupingBy(UserEntity::getAge, Collectors.mapping(UserEntity::getUserName, Collectors.joining(","))));
log.info(collect1.toString());

输出:

{20=[UserEntity(userName=langjialing, password=123, age=20), UserEntity(userName=langjialing456, password=456, age=20)], 25=[UserEntity(userName=langjialing789, password=789, age=25), UserEntity(userName=langjialing, password=123, age=25)]}
{20=langjialing,langjialing456, 25=langjialing789,langjialing}

Map<Long, List<UserEntity>> collect = list.stream().collect(Collectors.groupingBy(UserEntity::getAge)); 使用 collect() 方法将这个列表中的 UserEntity 对象按照它们的 age 属性进行分组,生成一个 Map<Long, List<UserEntity>> 对象。其中,Long 表示年龄,List<UserEntity> 表示该年龄对应的所有 UserEntity 对象的列表。

具体地说,这行代码使用了 Collectors.groupingBy() 方法,它接受一个函数作为参数,该函数用于将列表中的元素分组。在这个例子中,UserEntity::getAge 表示使用 UserEntity 对象的 getAge() 方法的返回值作为分组依据。这样,collect 对象就会包含按年龄分组后的所有 UserEntity 对象。

总结

本文介绍了把 List 中的元素按照某一条件进行分组。

赞助页面示例