java数据流分组操作如何做

avatar
作者
筋斗云
阅读量:0

在Java中,可以使用流操作来对数据进行分组。一种常见的方法是使用Collectors.groupingBy()方法来对数据流进行分组操作。示例如下:

假设有一个包含Person对象的数据流,每个Person对象有一个age属性,现在想要将数据流按照age属性进行分组操作,可以使用以下代码:

List<Person> personList = Arrays.asList(         new Person("Alice", 25),         new Person("Bob", 30),         new Person("Cathy", 25),         new Person("David", 40) );  Map<Integer, List<Person>> groupedByAge = personList.stream()         .collect(Collectors.groupingBy(Person::getAge));  groupedByAge.forEach((age, persons) -> {     System.out.println("Age: " + age);     persons.forEach(person -> System.out.println(person.getName())); }); 

在上面的示例中,使用Collectors.groupingBy()方法将Person对象按照age属性进行分组操作,得到了一个Map<Integer, List>,其中key是age属性,value是对应的Person列表。然后遍历Map,打印出每个age对应的Person列表。

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!