1.filter 过滤
List<String> lines = Arrays.asList("spring", "node", "mkyong","mkyong");
//从集合中获取过滤后生成的集合
List<String> list = lines.stream().filter(line-> !"mkyong".equals(line)).collect(Collectors.toList());
List<Person> persons = Arrays.asList(new Person("michael", 20),new Person("michael", 21), new Person("lawrence", 23));
//返回集合匹配到的第一个的age,如果都找不到返回orElse里面的值
Integer age = persons.stream().filter(x -> "michael".equals(x.getName())).map(Person::getAge).findFirst().orElse(null);
System.out.println(age);
2.map获取集合对象中指定元素集合(流)
List<Integer> l = persons.stream().filter(x -> "michael".equals(x.getName())).map(Person::getAge).collect(Collectors.toList());
System.out.println(l);//[20,21]
collect将流变成各种结果(收集器)
findAny返回集合流中任意一个个对象(一般返回第一个,并行时可能不会是第一个)
findFirst:返回流集合中第一个
3.groupby分组
//1.分组计数
List<Student> list1= Arrays.asList(
new Student(1,"one","zhao"),new Student(2,"one","qian"),new Student(3,"two","sun"));
//1.1根据某个属性分组计数
Map<String,Long> result1=list1.stream().collect(Collectors.groupingBy(Student::getGroupId,Collectors.counting()));
System.out.println(result1);
//1.2根据整个实体对象分组计数,当其为String时常使用
Map<Student,Long> result2=list1.stream().collect(Collectors.groupingBy(Function.identity(),Collectors.counting()));
System.out.println(result2);
//1.3根据分组的key值对结果进行排序、放进另一个map中并输出
Map<String,Long> xMap=new HashMap<>();
result1.entrySet().stream().sorted(Map.Entry.<String,Long>comparingByKey().reversed()) //reversed不生效
.forEachOrdered(x->xMap.put(x.getKey(),x.getValue()));
System.out.println(xMap);
//2.分组,并统计其中一个属性值得sum或者avg:id总和
Map<String,Integer> result3=list1.stream().collect(
Collectors.groupingBy(Student::getGroupId,Collectors.summingInt(Student::getId))
);
System.out.println(result3);