分区返回的是键为boolean值得Map对象,分组返回的是一个键为分组时使用的成员变量值的Map对象
package com.ydlclass.feature;
import org.junit.Before;
import org.junit.Test;
import java.util.*;
import java.util.function.Consumer;
import java.util.function.IntBinaryOperator;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class LambdaTest {
List<Person> personList = new ArrayList<>();
List<Integer> simpleList = Arrays.asList(15,22,9,11,33,52,14);
@Before
public void initData(){
personList.add(new Person("张三",3000,23,"男","太原"));
personList.add(new Person("李四",7000,34,"男","西安"));
personList.add(new Person("王五",5200,22,"女","西安"));
personList.add(new Person("小黑",1500,33,"女","上海"));
personList.add(new Person("狗子",8000,44,"女","北京"));
personList.add(new Person("铁蛋",6200,36,"女","南京"));
}
@Test
public void groupTest(){
//partitioningBy()其中需要传入一个断言
Map<Boolean, List<Person>> collect = personList.stream().collect(Collectors.partitioningBy(person -> person.getSalary() > 5000));
//所有为真的放在键为True的map'中
System.out.println(collect);
/***
* 输出的结果为:
* {false=[Person{name='张三', salary=3000, age=23, sex='男', area='太原'}, Person{name='小黑', salary=1500, age=33, sex='女', area='上海'}],
* true=[Person{name='李四', salary=7000, age=34, sex='男', area='西安'}, Person{name='王五', salary=5200, age=22, sex='女', area='西安'}, Person{name='狗子', salary=8000, age=44, sex='女', area='北京'}, Person{name='铁蛋', salary=6200, age=36, sex='女', area='南京'}]}
*/
System.out.println(collect.get(true));
System.out.println(collect.get(false));
Map<String, List<Person>> collect1 = personList.stream().collect(Collectors.groupingBy(person -> person.getSex()));
System.out.println(collect1);
/***输出结果
* {女=[Person{name='王五', salary=5200, age=22, sex='女', area='西安'}, Person{name='小黑', salary=1500, age=33, sex='女', area='上海'}, Person{name='狗子', salary=8000, age=44, sex='女', area='北京'}, Person{name='铁蛋', salary=6200, age=36, sex='女', area='南京'}],
* 男=[Person{name='张三', salary=3000, age=23, sex='男', area='太原'}, Person{name='李四', salary=7000, age=34, sex='男', area='西安'}]}
*/
//拿到所有的男性
System.out.println(collect1.get("男"));
System.out.println(collect1.get("女"));
}
}