lambda操作集合

一、stream常用方法
在这里插入图片描述

  1. forEach

    List<String> one = new ArrayList<>();
    Collections.addAll(one, "迪丽热巴", "宋远桥", "苏星河", "老子", "庄子", "孙子");
    one.stream().forEach(System.out::println);
    
  2. count

    System.out.println(one.stream().count());
    
  3. filter

    one.stream().filter(s -> s.length() == 2).forEach(System.out::println);
    
  4. limit

    one.stream().limit(3).forEach(System.out::println);
    
  5. skip

    one.stream().skip(2).forEach(System.out::println);
    
  6. map

    Stream<String> original = Stream.of("11", "22", "33");
    Stream<Integer> result = original.map(Integer::parseInt);
    result.forEach(s -> System.out.println(s + 10));
    
  7. sorted

    Stream.of(33, 22, 11, 55)
    .sorted()
    .sorted((o1, o2) -> o2 - o1)
    .forEach(System.out::println);
    
  8. distinct

    Stream.of(22, 33, 22, 11, 33)
        .distinct()
        .forEach(System.out::println);
    
    //自定义对象distinct,自定义类型是根据对象的hashCode和equals来去除重复元素的。
    Stream.of(
        new Person("刘德华", 58),
        new Person("张学友", 56),
        new Person("张学友", 56),
        new Person("黎明", 52)
    ).distinct().forEach(System.out::println);
    
  9. match

    boolean b = Stream.of(5, 3, 6, 1)
    // .allMatch(e -> e > 0); // allMatch: 元素是否全部满足条件
    // .anyMatch(e -> e > 5); // anyMatch: 元素是否任意有一个满足条件
    .noneMatch(e -> e < 0); // noneMatch: 元素是否全部不满足条件
    
    System.out.println("b = " + b);
    
  10. find

    Optional<Integer> first = Stream.of(5, 3, 6, 1).findFirst();
    System.out.println("first = " + first.get());
    
    Optional<Integer> any = Stream.of(5, 3, 6, 1).findAny();
    System.out.println("any = " + any.get());
    
  11. max/min

    Optional<Integer> max = Stream.of(5, 3, 6, 1).max((o1, o2) -> o1 - o2);
    System.out.println("first = " + max.get());
    
    Optional<Integer> min = Stream.of(5, 3, 6, 1).min((o1, o2) -> o1 - o2);
    System.out.println("any = " + min.get());
    
  12. reduce

    int reduce = Stream.of(4, 5, 3, 9).reduce(0, (a, b) -> {
        System.out.println("a = " + a + ", b = " + b);
        return a + b;
    });
    
    int reduce2 = Stream.of(4, 5, 3, 9).reduce(0, (x, y) -> {
    	return Integer.sum(x, y);
    });
    
    int reduce3 = Stream.of(4, 5, 3, 9).reduce(0, Integer::sum);
    
    int max = Stream.of(4, 5, 3, 9).reduce(0, (x, y) -> {
    	return x > y ? x : y;
    });
    
    
    
  13. map+reduce

    // 求出所有年龄的总和
    int totalAge = Stream.of(
        new Person("刘德华", 58),
        new Person("张学友", 56),
        new Person("郭富城", 54),
        new Person("黎明", 52)
    ).map((p) -> p.getAge()).reduce(0, (x, y) -> x + y);
    System.out.println("totalAge = " + totalAge);
    
    // 找出最大年龄
    int maxAge = Stream.of(
        new Person("刘德华", 58),
        new Person("张学友", 56),
        new Person("郭富城", 54),
        new Person("黎明", 52)
    ).map((p) -> p.getAge()).reduce(0, (x, y) -> x > y ? x : y);
    System.out.println("maxAge = " + maxAge);
    
    // 统计 数字2 出现的次数
    int count = Stream.of(1, 2, 2, 1, 3, 2).map(i -> {
        if (i == 2) {
        	return 1;
        } else {
        	return 0;
        }
    }).reduce(0, Integer::sum);
    System.out.println("count = " + count);
    
  14. mapToInt

    
    
  15. concat

    Stream<String> streamA = Stream.of("张三");
    Stream<String> streamB = Stream.of("李四");
    Stream<String> result = Stream.concat(streamA, streamB);
    result.forEach(System.out::println);
    
  16. Stream综合案例

    List<String> one = List.of("迪丽热巴", "宋远桥", "苏星河", "老子", "庄子", "孙子", "洪七公");
    List<String> two = List.of("古力娜扎", "张无忌", "张三丰", "赵丽颖", "张二狗", "张天爱","张三");
    // 第一个队伍只要名字为3个字的成员姓名;
    // 第一个队伍筛选之后只要前3个人;
    Stream<String> streamOne = one.stream().filter(s -> s.length() == 3).limit(3);
    // 第二个队伍只要姓张的成员姓名;
    // 第二个队伍筛选之后不要前2个人;
    Stream<String> streamTwo = two.stream().filter(s -> s.startsWith("张")).skip(2);
    // 将两个队伍合并为一个队伍;
    // 根据姓名创建Person对象;
    // 打印整个队伍的Person对象信息。
    Stream.concat(streamOne, streamTwo).map(Person::new).forEach(System.out::println);
    
  17. 收集Stream流中的结果

    //1. 收集结果到集合中
    Stream<String> stream = Stream.of("aa", "bb", "cc");
    // List<String> list = stream.collect(Collectors.toList());
    // Set<String> set = stream.collect(Collectors.toSet());
    ArrayList<String> arrayList = stream.collect(Collectors.toCollection(ArrayList::new));
    HashSet<String> hashSet = stream.collect(Collectors.toCollection(HashSet::new));
    
    //2. 收集结果到数组中
    Stream<String> stream = Stream.of("aa", "bb", "cc");
    // Object[] objects = stream.toArray();
    // for (Object obj : objects) {
    // System.out.println();
    // }
    String[] strings = stream.toArray(String[]::new);
    for (String str : strings) {
    System.out.println(str);
    }
    
    //3. 对流中数据进行聚合计算
    Stream<Student> studentStream = Stream.of(
    new Student("赵丽颖", 58, 95),
    new Student("杨颖", 56, 88),
    new Student("迪丽热巴", 56, 99),
    new Student("柳岩", 52, 77));
    // 获取最大值
    // Optional<Student> collect = studentStream.collect(Collectors.maxBy((o1, o2) ->o1.getSocre() - o2.getSocre()));
    // 获取最小值
    // Optional<Student> collect = studentStream.collect(Collectors.minBy((o1, o2) ->o1.getSocre() - o2.getSocre()));
    // System.out.println(collect.get());
    // 求总和
    // int sumAge = studentStream.collect(Collectors.summingInt(s -> s.getAge()));
    // System.out.println("sumAge = " + sumAge);
    // 平均值
    // double avgScore = studentStream.collect(Collectors.averagingInt(s -> s.getSocre()));
    // System.out.println("avgScore = " + avgScore);
    // 统计数量
    // Long count = studentStream.collect(Collectors.counting());
    // System.out.println("count = " + count);
    
    //4. 对流中数据进行分组
    // 分组
    @Test
    public void testGroup() {
        Stream<Student> studentStream = Stream.of(
        new Student("赵丽颖", 52, 95),
        new Student("杨颖", 56, 88),
        new Student("迪丽热巴", 56, 55),
        new Student("柳岩", 52, 33));
        // Map<Integer, List<Student>> map =
        studentStream.collect(Collectors.groupingBy(Student::getAge));
        
        // 将分数大于60的分为一组,小于60分成另一组
        Map<String, List<Student>> map = studentStream.collect(Collectors.groupingBy((s) -> {
            if (s.getSocre() > 60) {
            	return "及格";
            } else {
            	return "不及格";
            }
        }));
        
        map.forEach((k, v) -> {
    		System.out.println(k + "::" + v);
    	});
    }
    
    //5. 对流中数据进行多级分组
    @Test
    public void testCustomGroup() {
        Stream<Student> studentStream = Stream.of(
        new Student("赵丽颖", 52, 95),
        new Student("杨颖", 56, 88),
        new Student("迪丽热巴", 56, 99),
        new Student("柳岩", 52, 77));
        Map<Integer, Map<String, List<Student>>> map =
        studentStream.collect(Collectors.groupingBy(s -> s.getAge(), Collectors.groupingBy(s -> {
            if (s.getSocre() >= 90) {
            	return "优秀";
            } else if (s.getSocre() >= 80 && s.getSocre() < 90) {
            	return "良好";
            } else if (s.getSocre() >= 80 && s.getSocre() < 80) {
            	return "及格";
            } else {
            	return "不及格";
            }
            })));
            map.forEach((k, v) -> {
            System.out.println(k + " == " + v);
        });
    }
    
    //6. 对流中的数据进行分区
    @Test
    public void testPartition() {
        Stream<Student> studentStream = Stream.of(
        new Student("赵丽颖", 52, 95),
        new Student("杨颖", 56, 88),
        new Student("迪丽热巴", 56, 99),
        new Student("柳岩", 52, 77));
        // partitioningBy会根据值是否为true,把集合分割为两个列表,一个true列表,一个false列表。
        Map<Boolean, List<Student>> map = studentStream.collect(Collectors.partitioningBy(s ->
        s.getSocre() > 90));
        map.forEach((k, v) -> {
        	System.out.println(k + " == " + v);
        });
    }
    
    //7. 对流中数据进行拼接
    @Test
    public void testJoining() {
        Stream<Student> studentStream = Stream.of(
        new Student("赵丽颖", 52, 95),
        new Student("杨颖", 56, 88),
        new Student("迪丽热巴", 56, 99),
        new Student("柳岩", 52, 77));
        String collect = studentStream
        .map(Student::getName)
        .collect(Collectors.joining(">_<", "^_^", "^v^"));
        System.out.println(collect);
    }
    
    
  • 16
    点赞
  • 45
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Lambda 表达式可以用于集合的过滤和映射等操作,以下是一个简单的集合过滤的例子: ``` List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); List<Integer> evenNumbers = numbers.stream() .filter(n -> n % 2 == 0) .collect(Collectors.toList()); ``` 在这个例子中,我们创建了一个整数列表 `numbers`,然后使用 Lambda 表达式对其进行过滤,只保留其中的偶数。具体来说,我们首先通过 `stream()` 方法将列表转化为一个流(Stream),然后使用 `filter()` 方法对流进行过滤,保留其中符合条件的元素,这里的条件是 `n % 2 == 0`,即取余操作的结果等于 0。最后,我们使用 `collect()` 方法将过滤后的结果转化为一个列表 `evenNumbers`。 此外,我们还可以使用 Lambda 表达式进行集合的映射操作,例如: ``` List<String> names = Arrays.asList("Tom", "Jerry", "Spike"); List<Integer> nameLengths = names.stream() .map(name -> name.length()) .collect(Collectors.toList()); ``` 在这个例子中,我们创建了一个字符串列表 `names`,然后使用 Lambda 表达式对其进行映射,将其中的每个字符串转化为其长度。具体来说,我们首先通过 `stream()` 方法将列表转化为一个流(Stream),然后使用 `map()` 方法对流进行映射,将其中的每个字符串转化为其长度,这里的表达式是 `name -> name.length()`。最后,我们使用 `collect()` 方法将映射后的结果转化为一个列表 `nameLengths`。 这些都是Lambda表达式在集合过滤和映射中的应用,Lambda表达式可以大大简化集合操作的代码,并提高代码的可读性和可维护性。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值