Stream流
快速创建List
User实体类中有 name,age,height 三个属性
public class User {
// 省略 get 和 set 方法 可以使用 Alt + insert 中的 getter和setter 生成
public User(String name, String age, int height) {
this.name = name;
this.age = age;
this.height = height;
}
private String name;
private String age;
private int height;
}
在main方法中创建三个对象,将对象添加到list集合中
public static void main(String[] args) {
User user1 = new User("张三", "18", 180);
User user2 = new User("李四", "18", 175);
User user3 = new User("王五", "19", 170);
// method 1: list.add() 使用集合中的 add()方法进行单个添加
List<User> list = new ArrayList<>();
list.add(user1);
list.add(user2);
list.add(user3);
// method 2: Stream.of 使用Stream中的 of()方法进行多个添加,并收集成List集合
List<User> list = Stream.of(user1, user2, user3).collect(Collectors.toList());
}
stream的使用
遍历:foreach
public static void main(String[] args) {
User user1 = new User("张三", "18", 180);
User user2 = new User("李四", "18", 175);
User user3 = new User("王五", "19", 170);
// method: Stream.of
List<User> userList = Stream.of(user1, user2, user3).collect(Collectors.toList());
// 遍历 foreach
userList.stream().forEach(user -> {
System.out.println(user.getName() + "-------" + user.getAge() + "-------" + user.getHeight());
});
}
筛选:filter
public static void main(String[] args) {
// 筛选 filter
List<Integer> integerList = Arrays.asList(7, 6, 9, 3, 8, 2, 1);
integerList.stream().filter(x -> x > 6).forEach(System.out::println);
}
聚合:max/min/count
比较常见的数据统计 max(最大值) min(最小) count(求和)
public static void main(String[] args) {
List<String> list = Arrays.asList("adnm", "admmt", "pot", "xbangd", "weoujgsd");
Optional<String> max = list.stream().max(Comparator.comparing(String::length));
Optional<String> min = list.stream().min(Comparator.comparing(String::length));
long count = list.stream().count();
System.out.println("最长字符串是:" + max.get());
System.out.println("最短字符串是:" + min.get());
System.out.println("list长度为:" + count );
}
映射:map
映射,可以将一个流的元素按照一定的映射规则映射到另一个流中。
map
:接收一个函数作为参数,该函数会被应用到每个元素上,并将其映射成一个新的元素。
public static void main(String[] args) {
List<String> list = Arrays.asList("adnm", "admmt", "pot", "xbangd", "weoujgsd");
List<String> strings = list.stream().map(String::toUpperCase).collect(Collectors.toList());
List<Integer> integerList = Arrays.asList(7, 6, 9, 3, 8, 2, 1);
List<Integer> integers = integerList.stream().map(x -> x + 3).collect(Collectors.toList());
System.out.println("String 转换为大写:" + strings);
System.out.println("integer 数量 +3:" + integers);
}
递约:reduce
归约,也称缩减,顾名思义,是把一个流缩减成一个值,能实现对集合求和、求乘积和求最值操作。
public static void main(String[] args) {
List<Integer> integerList = Arrays.asList(7, 6, 9, 3, 8, 2, 1);
// 求和
Optional<Integer> firstSum = integerList.stream().reduce((x, y) -> x + y);
Optional<Integer> secondSum = integerList.stream().reduce(Integer::sum);
Integer thirdSum = integerList.stream().reduce(0, Integer::sum);
System.out.println("第一次求和:" + firstSum.get() + "-----第二次求和:" + secondSum.get() + "-----第三次求和:" + thirdSum);
// 求乘积
Optional<Integer> multiplication = integerList.stream().reduce((x, y) -> x * y);
System.out.println("乘积:"+ multiplication.get());
}
收集: collect
collect
:收集,可以说是内容最繁多、功能最丰富的部分了。从字面上去理解,就是把一个流收集起来,最终可以是收集成一个值也可以收集成一个新的集合。
归集:toList/toMap/toSet
- toList:将结果转换为list集合
- toMap:将结果转换为Map集合
- toSet:将结果转换为Set集合
public static void main(String[] args) {
List<Integer> integerList = Arrays.asList(7, 6, 9, 3, 8, 7, 1);
List<Integer> toList = integerList.stream().filter(x -> x > 6).collect(Collectors.toList());
Set<Integer> toSet = integerList.stream().filter(x -> x > 6).collect(Collectors.toSet());
System.out.println("toList:" + toList);
System.out.println("toSet" + toSet);
User user1 = new User("张三", "18", 180);
User user2 = new User("李四", "18", 175);
User user3 = new User("王五", "19", 170);
// method: Stream.of
List<User> userList = Stream.of(user1, user2, user3).collect(Collectors.toList());
Map<String, User> toMap = userList.stream().filter(x -> x.getHeight() > 170).collect(Collectors.toMap(User::getName,u->u));
System.out.println("toMap" + toMap);
}
统计:count/summingInt
Collectors提供了一系列用于数据统计的静态方法:
- 计数:count
- 平均值:averagingInt、averagingLong、averagingDouble
- 最值:maxBy、minBy
- 求和:summingInt、summingLong、summingDouble
- 统计以上所有:summarizingInt、summarizingLong、summarizingDouble
public static void main(String[] args) {
User user1 = new User("张三", "18", 180);
User user2 = new User("李四", "18", 175);
User user3 = new User("王五", "19", 170);
// method: Stream.of
List<User> userList = Stream.of(user1, user2, user3).collect(Collectors.toList());
// count 与.count()一致
Long count = userList.stream().collect(Collectors.counting());
System.out.println("userList数量:" + count);
// 平均值
Double avg = userList.stream().collect(Collectors.averagingDouble(User::getHeight));
System.out.println("userList平均身高" + avg);
}
分组:groupingBy
- 分区:将stream按条件分为两个Map
- 分组:将集合分为多个Map
public static void main(String[] args) {
User user1 = new User("张三", "18", 180);
User user2 = new User("李四", "18", 175);
User user3 = new User("王五", "19", 170);
User user4 = new User("赵六", "19", 170);
// method: Stream.of
List<User> userList = Stream.of(user1, user2, user3, user4).collect(Collectors.toList());
// 按照年龄分组
Map<String, List<User>> ageGroupMap = userList.stream().collect(Collectors.groupingBy(User::getAge));
// 二次分组
Map<String, Map<Integer, List<User>>> secondGroupMap = userList.stream().collect(Collectors.groupingBy(User::getAge, Collectors.groupingBy(User::getHeight)));
System.out.println("按照年龄分组:" + ageGroupMap);
System.out.println("按照年龄分组后,在按照身高分组" + secondGroupMap);
}
接合:joining
joining可以将stream中的元素用特定的连接符(没有的话,则直接连接)连接成一个字符串。
public static void main(String[] args) {
List<String> list = Arrays.asList("A", "B", "C");
String string = list.stream().collect(Collectors.joining("-"));
System.out.println("拼接后的字符串:" + string);
}
排序:sorts
sorted,中间操作。有两种排序:
- sorted():自然排序,流中元素需实现Comparable接口
- sorted(Comparator com):Comparator排序器自定义排序
public static void main(String[] args) {
User user1 = new User("张三", "18", 180);
User user2 = new User("李四", "18", 175);
User user3 = new User("王五", "19", 170);
User user4 = new User("赵六", "19", 170);
// method: Stream.of
List<User> userList = Stream.of(user1, user2, user3, user4).collect(Collectors.toList());
List<String> sortsUserList = userList.stream().sorted(Comparator.comparing(User::getAge)).map(User::getName).collect(Collectors.toList());
System.out.println("排序后:"+ sortsUserList);
}
提取/组合
limit
limit()方法可以将流限制为指定的元素数。
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
List<Integer> collect = numbers.stream().limit(3).collect(Collectors.toList());
System.out.println(collect);
}
Skip(跳过)
skip()方法可跳过前N个元素
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
List<Integer> collect = numbers.stream().skip(2).collect(Collectors.toList());
System.out.println(collect);
}
Skip(跳过)
skip()方法可跳过前N个元素
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
List<Integer> collect = numbers.stream().skip(2).collect(Collectors.toList());
System.out.println(collect);
}