Stream流使用笔记

文章详细展示了如何使用JavaStream进行数字数组、字符串数组以及实体对象的操作,包括计算数组的和、最大值、最小值,字符串排序、过滤、转换,以及实体对象的去重和分组。此外,还提供了力扣1859题目的解决方案,即句子排序问题,以及Stream的分组转化和统计功能的应用实例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

对数字数组的操作:

        List<Integer> list = Arrays.asList(1, 3, 2, 8, 11, 4);
        Optional<Integer> reduceSum = list.stream().reduce(Integer::sum);
        System.out.println("所有数据的和:" + reduceSum);
        Optional<Integer> reduceMax = list.stream().reduce(Integer::max);
        System.out.println("所有数据的最大值:" + reduceMax);
        Optional<Integer> reduceMin = list.stream().reduce(Integer::min);
        System.out.println("所有数据的最小值:" + reduceMin.get());
        Optional<Integer> reduceTake = list.stream().reduce((x, y) -> x * y);
        System.out.println("所有数据的乘积:" + reduceTake);
        long countBig5 = list.stream().filter(x -> x > 5).count();
        System.out.println("大于5的子项的个数:" + countBig5);
        System.out.println("打印各项加5后的值");
        list.stream().map(x -> x + 5).forEach(System.out::println);

对字符串数组的操作:

        // 数组的创建
        List<String> integerList = Arrays.asList("tom", "jim", "jack", "loc", "length", "peat", "rabbit");
        List<String> collect1 = integerList.stream().sorted().collect(Collectors.toList());
        System.out.println("排序后内容:" + collect1);
        long endT = integerList.stream().filter(x -> x.charAt(x.length() - 1) == 't').count();
        System.out.println("以t结尾的子项的个数:" + endT);
        List<String> c = integerList.stream().filter(x -> x.contains("c")).map(String::toUpperCase).collect(Collectors.toList());
        System.out.println("含c的子项全大写:" + c);
        List<String> lengthOf4 = integerList.stream().filter(x -> x.length() == 4).collect(Collectors.toList());
        System.out.println("长度刚好为4的子项:" + lengthOf4);
        System.out.println("子项全大写:");
        integerList.stream().map(String::toUpperCase).forEach(System.out::println);
        List<String> collect = integerList.stream().filter(x -> !x.equals("tom")).collect(Collectors.toList());
        System.out.println("剔除出集合为\"tom\"的元素:" + collect);
        Optional<String> noTom = integerList.stream().filter(x -> !x.equals("tom")).findFirst();
        System.out.println("剔除出集合为\"tom\"的元素后的第一个元素为:" + noTom);
        long count = integerList.stream().filter(x -> x.indexOf('m') >= 0).count();
        System.out.println("集合中包含m的元素个数为:" + count);
        String stringStream = integerList.stream().map(String::toUpperCase).collect(Collectors.joining(","));
        System.out.println("集合元素全部大写,并用逗号拼接" + stringStream);
        Double aDouble = integerList.stream().collect(Collectors.averagingDouble(String::length));
        System.out.println("集合内元素长度的平均值" + aDouble);
        List<String> mOrMList = integerList.stream().filter(x -> x.contains("m") || x.contains("M")).collect(Collectors.toList());
        System.out.println("含有m或M的子项:" + mOrMList);
        List<String> lengthMax3 = integerList.stream().filter(x -> x.length() > 3).collect(Collectors.toList());
        System.out.println("子项长度大于3的:" + lengthMax3);
        List<String> removeJAndA = integerList.stream().filter(x -> x.contains("j")).filter(x -> x.contains("a")).collect(Collectors.toList());
        System.out.println("先过滤子项含j的,再在其中过滤含a的:" + removeJAndA);

对实体对象的去重操作:

List<User> list = Arrays.asList(new User("张三", 18, 0, "北京"), new User("张三", 18, 0, "北京"), new User("张三", 18, 0, "北京"), new User("李四", 18, 0, "北京"), new User("王五", 20, 1, "上海"), new User("赵六", 22, 0, "广州"));
// distinct去重,如果是实体类没有实现去重效果,可以重写equals和hashCode方法
List<User> distinctList = list.stream().distinct().collect(Collectors.toList());
System.out.println(distinctList);

// Collectors.groupingBy 方法,根据实体某一字段分组
Map<Date, List<ReviewAssessGradeRecord>> dateListMap = reviewAssessGradeRecordList.stream().collect(Collectors.groupingBy(ReviewAssessGradeRecord::getCreatedTime));

// Collectors.groupingBy 方法,根据实体某一字段分组,再统计对应的值
Map<Date, Double> collect = reviewAssessGradeRecordList.stream().collect(Collectors.groupingBy(ReviewAssessGradeRecord::getCreatedTime, Collectors.summingDouble(ReviewAssessGradeRecord::getSort)));

//判断一组对象里面有没有属性值是某个值
boolean ifThereIsA = reviewAssessGradeRecordList.stream().anyMatch(m -> "123456".equals(m.getId()));

场景示例(力扣 1859. 将句子排序):

一个 句子 指的是一个序列的单词用单个空格连接起来,且开头和结尾没有任何空格,每个单词都只包含小写或大写英文字母。

我们可以给一个句子添加 从 1 开始的单词位置索引 ,并且将句子中所有单词 打乱顺序 。

比方说,句子 “This is a sentence” 可以被打乱顺序得到 “sentence4 a3 is2 This1” 或者 “is2 sentence4 This1 a3” 。
给你一个 打乱顺序 的句子 s ,它包含的单词不超过 9 个,请你重新构造并得到原本顺序的句子。

class Solution {
    public String sortSentence(String s) {
        return Arrays.stream(s.split(" ")).sorted(Comparator.comparingInt(a -> Integer.parseInt(a.substring(a.length() - 1)))).map(x -> x.substring(0, x.length() - 1)).collect(Collectors.joining(" "));
    }
}

Stream 按指定分组转化为 Map :

// 按批次分组并转化为Map
Map<String, List<ReviewAssessHistory>> jointOffice = reviewAssessHistoryList.stream().collect(Collectors.groupingBy(ReviewAssessHistory::getReviewStartNum));

Stream 统计数组中各个元素的数量 :

在示例代码中,Collectors.toMap(k -> k, k -> 1, Integer::sum)这一部分可能不好理解,对于这里面的三个参数,第一个参数代表将arr中的每一个元素作为Map中的key,第二个参数代表每一个key所对应的value,在这里每一个元素都对应个数1,第三个参数代表,如果存在相同的key,该如何进行合并,这里通过使用Integer::sum,代表将具有相同key的元素进行合并时,其value进行相加,这样便实现了每个元素个数的统计。

    Map<String, Integer> collects1 = Arrays.stream(s1.split(" ")).collect(Collectors.toMap(k -> k, k -> 1, Integer::sum));

将List中的数据填充到指定实体中,返回实体列表:

List<TopicAttendUnit> topicAttendUnits = topicDTO.getAttendUnitIds().stream()
    .map(x -> new TopicAttendUnit(topicDTO.getId(), x)).collect(Collectors.toList());

利用 .map() 方法,将一个Stream的每个元素映射成另一个元素并转换成一个新的Stream。其中使用两个参的构造函数,生成实体,最后转为List列表。

为实体List中的数据赋值

List<AttachmentFile> attachmentFiles = topicDTO.getAttachmentFileList().stream()
	.peek(x ->{x.setDataType(MeetingConstant.DATA_TYPE_TOPIC);x.setDataId(topicDTO.getId());}).collect(Collectors.toList());

peek用于处理集合中元素(对象)的某个属性的值,但不改变元素(对象)的类型,其与map的区别在于:

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值