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);