jdk8-stream

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
List<People> list = new ArrayList<>();

//取前20个
list=list.stream().limit(20).collect(Collectors.toList());


//取属性
List<String> spuCodes = list.stream().map(People::getName).collect(Collectors.toList());

//拼接
List<Integer> numbers = ImmutableList.of(1, 2, 3, 4, 5);
String result = numbers.stream().map(Object::toString).collect(Collectors.joining(","));
String result = numbers.stream().collect(Collectors.joining(", ", "[", "]"));


//根据age对list分组 List<X> -> map<x.id,List<x>>
Map<String,List<People>> groupByAge = list.stream().collect(Collectors.groupingBy(People::getAge));

//根据age对list的属性分组 List<X> -> map<x.id,List<x.name>>

Map<Long,List<String>> exhibitionPitemMap = list.stream().collect(
Collectors.groupingBy(People::getLong, Collectors.mapping(People::getName, Collectors.toList())));


//根据age进行排序(reserve倒序)
List<People> peopleListSorted = list.stream().sorted(Comparator.comparing(People::getAge)
.reversed()).collect(Collectors.toList());


//提取age,并排序
List<String> ageList = list.stream().map(People::getAge).distinct().sorted().collect(Collectors.toList());



//提取年龄大于20的people
List<People> olderThan20 = list.stream().filter(e->Integer.parseInt(e.getAge()) > 20)
.collect(Collectors.toList());

//累加
BigDecimal totalMoney = list.stream().map(People::getMoney).reduce(BigDecimal.ZERO, BigDecimal::add);

list.stream().mapToLong(People::getAge).sum();


Long sum2 = list.stream().reduce(0L, Long::sum);


//过滤取单个值
People people = list.stream().filter(e->e.getAge().equals("20")).findFirst().orElse(null);



//查找流中最大值和最小值
List<Person> personList = generatePersonList();
Person olderOne = personList.stream().max(Comparator.comparing(Person::getAge)).orElse(null);
Person youngerOne = personList.stream().min(Comparator.comparing(Person::getAge)).orElse(null);

//对象去重
ArrayList<Person> collect = personList.stream().collect(Collectors.collectingAndThen(
Collectors.toCollection(() -> new TreeSet<>(Comparator.comparingInt(Person::getAge))),
ArrayList::new));


//转换成String[]
list..stream().toArray(String[]::new)


//拼接字符串
request.getModuleIdList().stream().map(x-> x.toString()).collect(Collectors.joining(","));


// List<x> -> Map<x.id,x>

//1,key存在重复时,会抛出异常
Map<Long, Person> id2Entity = personList.stream().collect(Collectors.toMap(Person::getId, x-> x));

//2,解决key重复异常情况
Map<Long, Person> entityMap= personList.stream().collect(Collectors.toMap(Person::getId, Function.identity(),(x,y) -> y));



//list 分割
int pageNum = (list.size()+ PAGE_SIZE -1) / PAGE_SIZE;
List<List<Long>> splitList = Stream.iterate(0, n->n+1).limit(pageNum).parallel()
.map(a-> list.stream().skip(a*PAGE_SIZE).limit(PAGE_SIZE).parallel().collect(Collectors.toList())).collect(Collectors.toList());