高度抽象的集合数据处理
1. 使用Stream流对List进行去重、去偶数,然后查找最大值
import java.util.Arrays;
import java.util.Comparator;
public class Stream1 {
public static void main(String[] args) {
int max = Arrays.asList(1,2,2,5,6,8,9)
.stream()
//去重
.distinct()
//去偶
.filter(n -> n%2 != 0)
//取最大
.max(Comparator.comparing(n -> n))
.get();
System.out.println(max);
}
}
2. 使用Stream流对List进行排序,然后取第一个值
import java.util.Arrays;
import java.util.Comparator;
public class Stream2 {
public static void main(String[] args) {
int first = Arrays.asList(1,2,2,5,6,8,9)
.stream()
//排序-升序
.sorted(Comparator.comparing(n -> n))
//取第一
.findFirst()
.get();
System.out.println(first);
int first_reversed = Arrays.asList(1,2,2,5,6,8,9)
.stream()
//排序-降序
.sorted(Comparator.comparing(n -> n,Comparator.reverseOrder()))
.findFirst()
.get();
System.out.println(first_reversed);
}
}
3. 使用Stream流对List进行求平均值、求和
import java.util.Arrays;
public class Stream3 {
public static void main(String[] args) {
//求平均值
double average = Arrays.asList(1,2,2,5,6,8,9)
.stream()
//对流中的元素执行一对一的转换
.mapToInt(n->n)
//返回流中所有元素的平均值
.average()
.getAsDouble();
System.out.println(average);
//求和
int sum = Arrays.asList(1,2,2,5,6,8,9)
.stream()
.mapToInt(n->n)
.sum();
System.out.println(sum);
}
}
4. 使用Stream流对List进行排序,按照age从大到小排序
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
public class Stream4 {
static class Person{
int age;
String name;
public Person(int age, String name) {
this.age = age;
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Person{" +
"age=" + age +
", name='" + name + '\'' +
'}';
}
}
static List<Person> list = Arrays.asList(
new Person(30,"王五"),
new Person(33,"张三"),
new Person(27,"李四")
);
public static void main(String[] args) {
System.out.println("排序前:"+list);
List<Person> personList = list
.stream()
.sorted(Comparator.comparing(n->n.getAge()))
.collect(Collectors.toList());
System.out.println("排序后:"+personList);
}
}