stream使用
# 1.list<DTO> 转list<String>
List<String> ids = dtos.stream().map(DTO::getId).distinct().collect(Collectors.toList());
1
# 2.list<DTO>转map<String,List<DTO>>
Map<String, List<DTO>> map = dtos.stream().collect(Collectors.groupingBy(DTO::getId));
1
# 3.list转map<key,value>
Map<Integer,String> map = dtos.stream().collect(Collectors.toMap(DTO::getId,DTO::getName));
1
# 4.list<DTO>转map<key,DTO>
# 指定key-value,value是对象本身,Function.identity()是简洁写法,也是返回对象本身,key 冲突的解决办法,这里选择第二个key覆盖第一个key
Map<Integer,DTO> map = dtos.stream().collect(Collectors.toMap(DTO::getId, Function.identity(),(key1,key2)->key2));
1
2
2
# 5.list<DTO>转string拼接
String str = dtos.stream().map(DTO::getId).collect(Collectors.joining(","));
1
# 6.list<DTO>求和
# mapToInteger 、 mapToDouble 等等
Integer returnCount = dtos.stream().mapToInteger(DTO::getNum).sum();
double returnCount = dtos.stream().mapToDouble(DTO::getNum).sum();
1
2
3
2
3
# 7.filter 过滤器使用
//需求 返回以大开头 长度为2的集合 然后打印出来
List<String> list = new ArrayList<>();
list.add("大佬");
list.add("大哥");
list.add("大哥大");
list.stream()
.filter(s -> s.startsWith("大"))
.filter(s -> s.length() == 2)
.forEach(System.out::println);
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
# 8.limit / skip / concat
通过 limit 方法可以对流进行截取,只取用前 n 个。
list.stream().limit(2);
通过 skip 方法可以对流进行截取,保留n后数组
list.stream().skip(2);
通过 concat 可以对流进行合并
Stream<String> concat = Stream.concat(list.stream(), list.stream());
1
2
3
4
5
6
2
3
4
5
6
上次更新: 2026/3/11 21:47:04