您的位置:首页 > 其它

Collectors.groupingBy 使用

2017-06-19 20:59 543 查看

Collectors.groupingBy 使用

本文主要介绍一下lambda表达式中的Collectors.groupingBy的使用。
//groupingBy使用
System.out.println("=======groupingBy==========");
Stream<Person> stream = Stream.of(new Person("1", "aa", "12"), new Person("1", "bb", "13"), new Person("3", "cc", "14"));
System.out.println(stream.collect(Collectors.groupingBy(x -> x.id)));

//groupingBy
Map<String, List<Person>> tempMap = Stream.of(new Person("1", "aa", "12"), new Person("1", "bb", "13"), new Person("3", "cc", "14"))
.collect(Collectors.groupingBy(x -> x.id));
for (String s : tempMap.keySet()) {
tempMap.get(s).stream().forEach(x -> System.out.println(x));
}

Map<Boolean, List<Integer>> collectGroup = Stream.of(1, 2, 3, 4)
.collect(Collectors.groupingBy(it -> it > 3));
System.out.println("collectGroup : " + collectGroup);


这里用到的Person类的代码:
class Person {
String id;
String name;
String age;

public String getId() {
return id;
}

public void setId(String id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getAge() {
return age;
}

public void setAge(String age) {
this.age = age;
}

public Person() {
}

public Person(String id, String name, String age) {
this.id = id;
this.name = name;
this.age = age;
}

@Override
public String toString() {
return "Person{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
", age='" + age + '\'' +
'}';
}
}


看一下运行结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: