Java-Stream

map

作用:将流中的每一个元素转换为另外一类元素

1
2
3
4
List<User> userList = new ArrayList<>();
List<UserDTO> result = userList.stream()
.map(user -> new UserDTO(user.getName(), user.getAge()))
.collect(Collectors.toList());

filter

作用:过滤流中的每一个元素,符合条件的保留下来

1
2
3
List<User> result = userList.stream()
.filter(user -> user.getAge()>18)
.collect(Collectors.toList());

sorted

作用:对元素进行排序

自然排序sorted():

1
2
3
List<User> result = userList.stream()
.sorted()
.collect(Collectors.toList());

自定义排序sorted(Comparator comparator) :

1
2
3
List<User> result = userList.stream()
.sorted(Comparator.comparingInt(User::getAge))
.collect(Collectors.toList());

反转排序

1
2
3
List<User> result = userList.stream()
.sorted(Comparator.comparingInt(User::getAge).reversed())
.collect(Collectors.toList());

limit

作用:返回的集合最多包涵的元素个数

1
2
3
List<User> result = userList.stream()
.limit(2)
.collect(Collectors.toList());

allMatch

作用:所有元素都匹配成功返回true

1
2
boolean result = userList.stream()
.allMatch(user -> user.getAge()>18);

anyMatch

作用:任意一个元素匹配成功返回true

1
2
boolean result = userList.stream()
.anyMatch(user -> user.getAge()>18);

max/min

作用:返回规则中结果最大/最小的一个元素

1
2
User result = userList.stream()
.max(Comparator.comparingInt(User::getAge)).get();

reduce

作用:聚合操作,根据规则将流中的元素计算后返回一个唯一的值

1
2
3
//返回年龄最大的User
User result = userList.stream()
.reduce((user1, user2) -> user1.getAge()>user2.getAge()?user1:user2).get();

带有初始值的

1
2
3
4
//在100基础上,加每一个user的年龄
int sum = userList.stream()
.map(User::getAge)
.reduce(100, ((age1, age2) -> age1 + age2));

forEach

作用:迭代元素,

注意:不能continue;break;return;不能修改外部变量值

1
2
3
list.forEach(System.out::println);

map.forEach((k, v) -> System.out.println(k+"->"+v));

collect

作用:对流数据进行归集

1
<R, A> R collect(Collector<? super T, A, R> collector);

Collectors可以创建多种Collector的实现

Collectors.toList()收集为一个list

Collectors.toMap()收集为一个map,用于list转map

1
2
3
把用户集合转为key是name,value是age的map
Map<String, Integer> result = userList.stream()
.collect(Collectors.toMap(User::getName, User::getAge));

Collectors.toSet()

Collectors.toCollection() :⽤⾃定义的实现Collection的数据结构收集

  • Collectors.toCollection(LinkedList::new)
  • Collectors.toCollection(CopyOnWriteArrayList::new)
  • Collectors.toCollection(TreeSet::new)

joining

作用:拼接字符串

直接拼接

1
String r = userList.stream().map(User::getName).collect(Collectors.joining());

以逗号分隔符拼接(可以换其它符号)

1
String r = userList.stream().map(User::getName).collect(Collectors.joining(","));

以括号开头和结尾逗号分隔拼接(可以换其它符号)

1
String r = userList.stream().map(User::getName).collect(Collectors.joining(",","(",")"));