Java小知识点之lambda

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

 List<Person> 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<Long> 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<Person> personList = listPerson();
List<String> nameList = personList.stream().map(Person::getName).collect(Collectors.toList());
System.out.println("转换后数据:" + nameList);

在这里插入图片描述

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

List<Long> 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<String> cities = Arrays.asList("Milan", "London", "New York", "San Francisco");
String nameStr = String.join(",", cities);
System.out.println("转换后数据:" + nameStr);

在这里插入图片描述

5、过滤

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

在这里插入图片描述

6、排序

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

在这里插入图片描述

降序

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

在这里插入图片描述

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

排序存在空数据的处理方式:

  List<Demo> testList = new ArrayList<Demo>();
        testList.add(getDemo("aa"));
        testList.add(getDemo("bb"));
        testList.add(getDemo("cc"));
        testList.add(getDemo("dd"));
        testList.add(null);
        testList.add(getDemo("ee"));
        testList.stream().sorted(Comparator.comparing(Demo::getName, Comparator.nullsFirst(String::compareTo))).collect(Collectors.toList());
        testList.stream().sorted(Comparator.comparing(Demo::getName, Comparator.nullsLast(String::compareTo))).collect(Collectors.toList());

根据map的key排序:

excelMap.entrySet().stream().sorted(Map.Entry.comparingByKey()).forEachOrdered(it -> excelLevelMap.put(it.getKey(), it.getValue()) );

7、list转map

List<Person> personList = listPerson();
System.out.println("转map前数据:"+ personList);
Map<String,Person> 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));
在这里插入图片描述
Java 8允许在接口中加入具体方法。接口中的具体方法有两种,default方法和static方法,identity()就是Function接口的一个静态方法。
Function.identity()返回一个输出跟输入一样的Lambda表达式对象,等价于形如t -> t形式的Lambda表达式
在这里插入图片描述

Map<String, Person> collect = personList.stream().collect(Collectors.toMap(Person::getName, Function.identity()));

8、根据某个字段分组

List<Person> personList = listPerson();
System.out.println("分组前数据:"+ personList);
Map<String, List<Person>> 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<Person> personList = listPerson();
System.out.println("分组前数据:"+ personList);
LinkedHashMap<String, List<Person>> 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<Double> data = Arrays.asList(1d,9d,8d);
System.out.println("原始数据:" + data);
double avg = data.stream().mapToDouble(item->item).summaryStatistics().getAverage();
System.out.println("平均数据:" + avg);

在这里插入图片描述

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

在这里插入图片描述

11、字符串去重

 List<String> 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<Person> 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<String> 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<Integer> 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("随机数: ");

持续更新中…

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值