java字符串分组,Java 8按字符串分组

这篇博客讨论了如何使用Java Stream API对学生对象列表进行处理,根据学生的爱好进行分组。提供的代码示例中,存在一个问题导致无法正确分组。解决方案是通过创建一个由爱好和学生组成的映射,然后使用flatMap和groupingBy方法进行分组。这将按照学生的爱好聚合学生列表。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Here is my code:

public class StudentData {

public static List getData() {

return Arrays.asList(

new Student(1, "a1", 1, Arrays.asList("cricket", "football", "basketball")),

new Student(2, "a2", 1, Arrays.asList("chess", "football")),

new Student(3, "a3", 2, Arrays.asList("running")),

new Student(4, "a4", 2, Arrays.asList("throwball", "football")),

new Student(5, "a5", 3, Arrays.asList("cricket", "basketball")),

new Student(6, "a6", 4, Arrays.asList("cricket")), new Student(7, "a7", 5, Arrays.asList("basketball")),

new Student(8, "a8", 6, Arrays.asList("football")),

new Student(9, "a9", 8, Arrays.asList("tennis", "swimming")),

new Student(10, "a10", 8, Arrays.asList("boxing", "running")),

new Student(11, "a11", 9, Arrays.asList("cricket", "football")),

new Student(12, "a12", 11, Arrays.asList("tennis", "shuttle")),

new Student(13, "a13", 12, Arrays.asList("swimming"))

);

}

}

How to group the student based on hobbies. I tried this below code:

List data = StudentData.getData();

data.stream().collect(Collectors.groupingBy(s -> s.getHobbies().stream()));

It is not giving the right answer.

解决方案

You basically need a Stream that is made out of a Pair (I choose AbstractMap.SimpleEntry here) that has the left part as a Hobby and right as the Student (could be the other way around, does not matter).

Later just group those based on Hobby (that is a String in your case).

data.stream()

.flatMap(student -> student.getHobbies().stream().map(hobby -> new SimpleEntry<>(hobby, student)))

.collect(Collectors.groupingBy(

Entry::getKey,

Collectors.mapping(Entry::getValue, Collectors.toList())

));

Entry::getKey being a method reference that gets the key, you could write it as a lambda expression too, if it makes more sense for you:

Collectors.groupingBy(entry -> entry.getKey())

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值