博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Java小知识点之lambda
阅读量:4170 次
发布时间:2019-05-26

本文共 5956 字,大约阅读时间需要 19 分钟。

1、为集合中的某个字段统一赋值

List
personList = listPerson(); System.out.println("设置值之前数据:"+ personList); personList.forEach(person -> person.setAge(20)); System.out.println("设置值之后数据:" + personList);

在这里插入图片描述

2、将由,分割的字符串转换成Long的List

String idStr = "1,2,3,4,5,6,7,8";List
idList = new ArrayList<>(16);idList.addAll(Arrays.stream(idStr.split(",")).map(s -> Long.parseLong(s.trim())).collect(Collectors.toList()));System.out.println("转换后数据:" + idList);

在这里插入图片描述

3、原列表中存放的是对象,从原列表中取出对象的某个属性构成另一个列表

List
personList = listPerson();List
nameList = personList.stream().map(Person::getName).collect(Collectors.toList());System.out.println("转换后数据:" + nameList);

在这里插入图片描述

4、将Long集合转为,分割的字符串

List
idList = Arrays.asList(1L,2L,3L);System.out.println("转换前数据:" + idList);String ids =idList.stream().map(Object::toString).collect(Collectors.joining(","));System.out.println("转换后数据:" + ids);

在这里插入图片描述

List
cities = Arrays.asList("Milan", "London", "New York", "San Francisco");String nameStr = String.join(",", cities);System.out.println("转换后数据:" + nameStr);

在这里插入图片描述

5、过滤

List
personList = listPerson();System.out.println("过滤之前数据:"+ personList);personList = personList.stream().filter(person -> person.getAge() > 16).collect(Collectors.toList());System.out.println("设置值之后数据:" + personList);

在这里插入图片描述

6、排序

List
personList = listPerson();System.out.println("排序之前数据:"+ personList);personList = personList.stream().sorted(Comparator.comparing(Person::getAge)).collect(Collectors.toList());System.out.println("排序之后数据:" + personList);

在这里插入图片描述

降序

List
personList = listPerson();System.out.println("排序之前数据:"+ personList);personList = personList.stream().sorted(Comparator.comparing(Person::getAge).reversed()).collect(Collectors.toList());System.out.println("排序之后数据:" + personList);

在这里插入图片描述

// 数据格式:List
>Collections.sort(list, new Comparator
>(){
public int compare(Map
o1, Map
o2) { String name1 =(String)o1.get("id");//name1是从你list里面拿出来的一个 String name2= (String)o2.get("id"); //name1是从你list里面拿出来的第二个name return name1.compareTo(name2); }});

7、list转map

List
personList = listPerson();System.out.println("转map前数据:"+ personList);Map
personMap = personList.stream().collect(Collectors.toMap(Person::getName,person -> person));System.out.println("转map之后数据:" + personMap);

在这里插入图片描述

在使用 java.util.stream.Collectors 类的 toMap()方法转为 Map 集合时,一定要使
用含有参数类型为 BinaryOperator,参数名为 mergeFunction 的方法,否则当出现相同 key 值时会抛出 IllegalStateException 异常

比如:

转map前的数据如下:
在这里插入图片描述
这个时候使用name作为map的key,则会抛异常:
在这里插入图片描述
解决方法:指定若出现重复,取哪个数据
Map<String,Person> personMap = personList.stream().collect(Collectors.toMap(Person::getName,person -> person,(person1,person2)->person2));
在这里插入图片描述

8、根据某个字段分组

List
personList = listPerson();System.out.println("分组前数据:"+ personList);Map
> personMap = personList.stream().collect(Collectors.groupingBy(Person::getName));System.out.println("分组后数据:"+ personMap);

在这里插入图片描述

        遇到一个小问题,查询出来一组数据后,按照其中的属性进行groupBy 分组 ,分组后要保证顺序不变。但是实际用groupBy进行分组后,返回的数据是杂乱无章的,没有按照原来list 的顺序返回

        通过java api 发现 groupingBy 调用是内部自己创建了一个 HashMap ( HashMap::new)。因为 hashMap,是无无序的,是根据key的hashcode进行hash,然后放入对应的地方。所以在按照一定顺序put进HashMap中,然后遍历出HashMap的顺序跟put的顺序不同。

保证顺序,代码如下:

List
personList = listPerson();System.out.println("分组前数据:"+ personList);LinkedHashMap
> personMap = personList.stream().collect(Collectors.groupingBy(Person::getName,LinkedHashMap::new,Collectors.toList()));System.out.println("分组后数据:"+ personMap);

在这里插入图片描述

9、判断是否存在相同的属性

boolean anyMatch = list.stream().anyMatch(item -> Objects.equals(item.getLevel(), level));

10、获取平均值、最大值、最小值

List
data = Arrays.asList(1d,9d,8d);System.out.println("原始数据:" + data);double avg = data.stream().mapToDouble(item->item).summaryStatistics().getAverage();System.out.println("平均数据:" + avg);

在这里插入图片描述

List
data = Arrays.asList(234,56,787,99,433,6);System.out.println("原始数据:" + data);Optional
maxValue = data.stream().max(Comparator.comparingInt(item-> item));System.out.println("最大值:" + maxValue.get());Optional
mixValue = data.stream().min(Comparator.comparingInt(item-> item));System.out.println("最小值:" + mixValue.get());

在这里插入图片描述

11、字符串去重

List
strList = Arrays.asList("qqq", "aaa", "bbb", "aaa"); strList = strList.stream().distinct().collect(Collectors.toList()); System.out.println("去重后数据:" + strList);

在这里插入图片描述

distinct()返回由该流的不同元素组成的流。

distinct()是Stream接口的方法。
distinct()使用hashCode()和equals()方法来获取不同的元素。因此,我们的类必须实现hashCode()和equals()方法。如果distinct()正在处理有序流,那么对于重复元素,将保留以遭遇顺序首先出现的元素,并且以这种方式选择不同元素是稳定的。

12、根据某个字段去重

List
personList = listPerson();System.out.println("去重前数据:"+ personList);personList = personList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Person :: getName))), ArrayList::new));System.out.println("去重后数据:" + personList);

在这里插入图片描述

13、是否存在某个元素

List
strList = Arrays.asList("aaa", "sss", "aaa", "aaa");boolean anyMatchA = strList.stream().anyMatch(item -> Objects.equals(item, "aaa"));System.out.println("是否存在aaa:" + anyMatchA);boolean allMatchA = strList.stream().allMatch(item -> Objects.equals(item, "aaa"));System.out.println("是否全部为aaa:" + allMatchA);boolean noneMatch = strList.stream().noneMatch(item -> Objects.equals(item, "aaa"));System.out.println("是否不存在aaa:" + noneMatch);

在这里插入图片描述

boolean anyMatch(Predicate<? super T> predicate)

只要有一个条件满足即返回true
boolean allMatch(Predicate<? super T> predicate)
必须全部都满足才会返回true
boolean noneMatch(Predicate<? super T> predicate)
全都不满足才会返回true

14、收集器

一些产生统计结果的收集器也非常有用。它们主要用于int、double、long等基本类型上,

List
integers = Arrays.asList(1,2,13,4,15,6,17,8,19);IntSummaryStatistics stats = integers.stream().mapToInt((x) ->x).summaryStatistics(); System.out.println("列表中最大的数 : " + stats.getMax()); System.out.println("列表中最小的数 : " + stats.getMin()); System.out.println("所有数之和 : " + stats.getSum()); System.out.println("平均数 : " + stats.getAverage()); System.out.println("随机数: ");

持续更新中…

转载地址:http://gayai.baihongyu.com/

你可能感兴趣的文章
Python 迭代器(iterator)
查看>>
Python enumerate类
查看>>
leetcode 99 Recover Binary Search Tree (python)
查看>>
linux echo 向文件中追加信息
查看>>
区块链问与答
查看>>
css常用小知识点
查看>>
js常用小知识点
查看>>
Java常用小知识点
查看>>
Java小知识点之lambda
查看>>
开源Java诊断工具Arthas简单使用说明
查看>>
深入理解Mysql索引底层数据结构与算法(二)
查看>>
IDEA自动去掉无用的import
查看>>
js数字转换成汉字
查看>>
MySQL不同存储引擎底层真正存储结构
查看>>
MySQL存储引擎底层常见面试题
查看>>
MySQL Explain执行计划详解
查看>>
索引最佳实践具体实例
查看>>
临时关闭MySQL缓存
查看>>
HBase学习和使用
查看>>
LSTM
查看>>