List<Person> list = new ArrayList<>();
Person p = new Person("zmm1",18,18);
list.add(p);
list.add(p);
list.add(new Person("zmm3",2,18));
list.add(new Person("zmm2",3,18));
去重
System.out.println("=============去重================");
List<Person> distinctList = list.stream().distinct().collect(Collectors.toList());
distinctList.stream().forEach(item ->{
System.out.println(item);
});
过滤
System.out.println("=============过滤================");
List<Person> filterList = list.stream().filter(item->item.getAge()>3).collect(Collectors.toList());
filterList.stream().forEach(item->{
System.out.println(item);
});
map()
System.out.println("=============map()================");
// 提取对象中的某一元素. 用每一项来获得属性(也可以直接用 对象::get属性())
List<String> mapList = list.stream().map(Person::getName).collect(Collectors.toList());
mapList.stream().forEach(o->{
System.out.println(o);
});
统计
System.out.println("=============统计================");
Integer age = list.stream().mapToInt(Person::getAge).sum();
System.out.println(age);
分组
//Collectors.groupingBy(属性名)
System.out.println("=============分组================");
Map<Integer, List<Person>> map = list.stream().collect(Collectors.groupingBy(Person::getAge));
map.forEach((s,L)->{
System.out.println(s+" "+L);
});
排序
//排序 sorted((第一个对象,第二个对象)->返回值) (升降序看是第几个对象与第几个对象比较)
//升序(o1,o2)->o1.getAge()-o2.getAge()
//降序(o1,o2)->o2.getAge()-o1.getAge()
System.out.println("=============排序================");
List<Person> sortedList = list.stream().sorted((o1,o2)->o1.getAge()-o2.getAge()).collect(Collectors.toList());
sortedList.stream().forEach(o->{
System.out.println(o);
});
List转Map
Map<String,Object> map = list.stream().collect(Collectors.toMap(Object::getId,Object::getName));
//1.重复的key问题
//对于重复key问题,源码中有一个说明,意思是若key存在重复,会抛出IllegalStateException异常,应使用toMap(Function, Function, BinaryOperator)方法。
//下面的写法就提供了一个取值的方法 (k1,k2) -> k1,如果k1和k2相等,取k1作为key
Map<String, String> map= list.stream().collect(Collectors.toMap(Object::getId,Object::getName,(k1,k2) -> k1));
//2.value为null问题
//HashMap在使用的时候是允许key和value都为null的,但在这里key可以为null,但是value不允许为null,来看源码的实现,在进行合并的时候,对value进行了非空的校验,不允许vallue为空,所以在toMap之前要先把value为空的数据过滤掉,Stream提供了一个filter的过滤方法
Map<String, String> map= list.stream().filter(t -> StringUtils.isNotBlank(t.getName())).collect(Collectors.toMap(Object::getId,Object::getName));
Map<String, String> map = list.stream().collect(Collectors.toMap(item -> item.getVersion(), item -> item.getGroupCode(), (oldVal, currVal) -> oldVal, LinkedHashMap::new));