Java8的stream使用示例
2021-03-02 15:07:45
Stream API 可以极大提高 Java 程序员的生产力,让程序员写出高效率、干净、简洁的代码
```
package com.example;
import java.util.*;
import java.util.stream.Collectors;
import static java.util.stream.Collectors.toList;
import static java.util.stream.Collectors.toSet;
class Foo {
private int num;
public Foo(int num) {
this.num = num;
}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
@Override
public String toString() {
return "Foo{" + "num=" + num + '}';
}
}
public class Demo {
public static void main(String[] args) {
List<Foo> list = new ArrayList<>();
list.add(new Foo(3));
list.add(new Foo(8));
list.add(new Foo(2));
list.add(new Foo(5));
list.add(new Foo(2));
// 过滤筛选 (只留下偶数)
List<Foo> list2 = list.stream().filter((a) -> {
return a.getNum() % 2 == 0;
}).collect(toList());
System.out.println(list2);
// 倒序
List<Foo> list3 = list.stream().sorted(Comparator.comparing(Foo::getNum).reversed()).collect(toList());
System.out.println(list3);
// 倒序
List<Foo> list4 = list.stream().sorted((a, b) -> {
return a.getNum() < b.getNum() ? 1 : -1;
}).collect(toList());
System.out.println(list4);
// 得取某一字段值,并去重
Set<Integer> numbers = list.stream().map((item) -> {
return item.getNum();
}).collect(toSet());
System.out.println(numbers);
// 转Map,指定列作为key。下面这种方式,Key冲突时会抛异常 java.lang.IllegalStateException: Duplicate key Foo{num=2}
// Map<Integer, Foo> fooMap = list.stream().collect(Collectors.toMap(Foo::getNum, item -> item));
// key冲突时使用后一个覆盖前一个同名key的value
Map<Integer, Foo> fooMap = list.stream().collect(Collectors.toMap(Foo::getNum, item -> item, (n1, n2) -> { return n2; }));
// 第四个参数 用于自定义返回 Map 类型,比如我们希望返回的 Map 是根据 Key 排序的,可以使用如下写法
// Map<Integer, Foo> fooMap = list.stream().collect(Collectors.toMap(Foo::getNum, item -> item, (n1, n2) -> { return n2; }, TreeMap::new));
System.out.println(fooMap);
// 以某个属性分组
Map<Integer, List<Foo>> listMap = list.stream().collect(Collectors.groupingBy(Foo::getNum));
System.out.println(listMap);
// Set to List
Set<String> nameSet = new HashSet<String>() {{
add("jack");
add("mary");
}};
// List<String> nameList = nameSet.stream().collect(toList());
List<String> nameList = new ArrayList<>(nameSet);
System.out.println(nameList);
}
}
```
运行结果如下:
```
[Foo{num=8}, Foo{num=2}, Foo{num=2}]
[Foo{num=8}, Foo{num=5}, Foo{num=3}, Foo{num=2}, Foo{num=2}]
[Foo{num=8}, Foo{num=5}, Foo{num=3}, Foo{num=2}, Foo{num=2}]
[2, 3, 5, 8]
{2=Foo{num=2}, 3=Foo{num=3}, 5=Foo{num=5}, 8=Foo{num=8}}
{2=[Foo{num=2}, Foo{num=2}], 3=[Foo{num=3}], 5=[Foo{num=5}], 8=[Foo{num=8}]}
[mary, jack]
```
去重
```
List<Integer> list = new ArrayList<>();
list.add(1);
list.add(1);
list.add(4);
list.add(2);
list.add(4);
List<Integer> list2 = list.stream().distinct().collect(Collectors.toList());
System.out.println(list2);
```
得到如下结果:
[1, 4, 2]