1、Collectors.maxBy()/minBy()的使用
Collectors.maxBy()
/minBy()
可以根据指定的Comparator,计算stream中的最大值和最小值,例如,
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Main {
public static class Person {
int age;
Person (int age) {
this.age = age;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
public static void main(String[] args) {
List<Person> pList = Arrays.asList(new Person(11),new Person(22), new Person(33), new Person(44), new Person(55));
Optional<Integer> maxByResult = pList.stream().map(p -> p.getAge()).collect(Collectors.maxBy(Comparator.naturalOrder()));
System.out.println("stream() maxByResult :" + maxByResult.get());
Optional<Integer> minByResult = pList.stream().map(p -> p.getAge()).collect(Collectors.minBy(Comparator.naturalOrder()));
System.out.println("stream() minByResult :" + minByResult.get());
System.exit(0); //success
}
}
2、Collectors.groupingBy()的使用
Collectors.groupingBy()
根据指定的属性进行分组,并返回一个Map,例如,
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Main {
public static class Person {
int age;
Person (int age) {
this.age = age;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
public static void main(String[] args) {
List<Person> pList = Arrays.asList(new Person(11),new Person(11),new Person(22), new Person(33), new Person(44), new Person(55));
Map<Integer, Set<Person>> groupByResult = pList.stream()
.collect(Collectors.groupingBy(Person::getAge,Collectors.toSet()));
System.out.println("stream() groupByResult :" + groupByResult);
System.exit(0); //success
}
}
3、Collectors.partitioningBy()的使用
Collectors.partitioningBy()
返回一个Map,这个Map是以boolean
值为key,将stream分成两部分,一部分是匹配PartitioningBy
条件的,另一部分是不满足条件的:,如下,
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Main {
public static class Person {
int age;
Person (int age) {
this.age = age;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
public static void main(String[] args) {
List<Person> pList = Arrays.asList(new Person(11),new Person(11),new Person(22), new Person(33), new Person(44), new Person(55));
Map<Boolean, List<Person>> partitionResult = pList.stream()
.collect(Collectors.partitioningBy(p -> p.getAge() > 22));
System.out.println("stream() groupByResult :" + partitionResult);
System.exit(0); //success
}
}