根据单/多字段分组
单字段分组可以直接使用指定字段,多字段分组则采用拼接Key的形式
单字段:
//单字段分组
Map<String, List<User>> singleAttr = list.stream().collect(
Collectors.groupingBy(t -> t.getNativePlace()));
//还可以写成简化版
//Map<String, List<User>> collect = list.stream().collect(
// Collectors.groupingBy(User::getNativePlace));
多字段:文章来源:https://www.toymoban.com/news/detail-618102.html
//多字段分组
Map<String, List<User>> multiAttr = list.stream().collect(
Collectors.groupingBy(t -> t.getNativePlace()+"_"+t.getAge()));
多层级:文章来源地址https://www.toymoban.com/news/detail-618102.html
//多级分组
Map<String, Map<Integer, List<User>>> multiLevel = list.stream().collect(
Collectors.groupingBy(
t -> t.getNativePlace(),
Collectors.groupingBy(t -> t.getAge())
)
);
测试
package test;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
public class Test {
public static void main(String[] args) {
ArrayList<User> list=new ArrayList<User>();
list.add(new User(11,"a"));
list.add(new User(12,"a"));
list.add(new User(14,"c"));
list.add(new User(14,"c"));
//单字段分组
Map<String, List<User>> singleAttr = list.stream().collect(Collectors.groupingBy(t -> t.getNativePlace()));
//还可以写成简化版
//Map<String, List<User>> collect = list.stream().collect(Collectors.groupingBy(User::getNativePlace));
//多字段分组
Map<String, List<User>> multiAttr = list.stream().collect(Collectors.groupingBy(t -> t.getNativePlace()+"_"+t.getAge()));
//多级分组
Map<String, Map<Integer, List<User>>> multiLevel = list.stream().collect(
Collectors.groupingBy(
t -> t.getNativePlace(),
Collectors.groupingBy(t -> t.getAge())
)
);
}
}
class User{
private int age;
private String nativePlace;
public String getNativePlace() {
return nativePlace;
}
public void setNativePlace(String nativePlace) {
this.nativePlace = nativePlace;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public User(int age,String nativePlace) {
this.age = age;
this.nativePlace=nativePlace;
}
}
到了这里,关于Java stream 分组操作的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!