ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

JDK1.8常用语法

2020-03-02 10:06:22  阅读:715  来源: 互联网

标签:toList JDK1.8 stream Collectors 元素 常用 语法 collect asList


stream 部分用法https://mp.weixin.qq.com/s/yS61Bbvlj5eOfEGpJR4gQA

 

Max和Min

// 求对象某属性的最小值
Ab ab = list.stream().min(Comparator.comparing(Ab::getCount)).get();
// 直接求最小值
Integer integer = Stream.of(8, 2, 3).min(Comparator.comparing(Integer::intValue)).get();

Map(T -> R)

替换list中的某个值,将流中的每一个元素T映射为R(类似类型转换)

# map用法, 将 list中的值都减1
lists.stream().map(aa -> aa - 1).collect(Collectors.toList());
#至取出对象中的某个属性
asList(new Ae("张三"), new Ae("李四"), new Ae("高五")).stream().map(Ae::getName).forEach(System.out::println);

flatMap

将list合并。将流中的每一个元素 T 映射为一个流,再把每一个流连接成为一个流

Stream.of(int1, int2).flatMap(as -> as.stream()).collect(Collectors.toList());
asList("aaa bbb ccc").stream()
        .map(a -> a.split(" ")).flatMap(Arrays::stream).collect(Collectors.toList()).forEach(System.out::println);

filter

过滤

System.out.println("先过滤再统计个数" + lists.stream().filter(geg -> geg == 1).count());

reduce

求和, 第一个参数是起始数,可以为空,acc是上一轮acc和当前元素的和,element为当前元素。

#1
Integer sumInt = asList(1, 2, 5).stream().reduce(0, (acc, element) -> acc + element);
# 2
Integer aaa = asList(1, 2, 5).stream().reduce( (acc, element) -> acc + element).get();

sorted

从小到大
asList(1, 2, 5).stream().sorted().collect(Collectors.toList());
#从大到小
asList(1, 2, 5).stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());
#从大到小
asList(1, 5,2,4,8).stream().sorted((a, b) -> b -a).collect(Collectors.toList()).forEach(System.out ::println);
#从大到小
list.stream().sorted(Comparator.comparingInt(Person::getAge    )).collect(Collectors.toList());

limit

    返回前n个元素

skip

    去除前n个元素

anyMatch

    是否有元素匹配。 还有allMatch、noneMatch

boolean b = asList(1, 2, 4).stream().anyMatch(a -> a == 2);

findAny() 和 findFirst()

findAny():找到其中一个元素 (使用 stream() 时找到的是第一个元素;使用 parallelStream() 并行时找到的是其中一个元素)

findFirst():找到第一个元素

 

面试问过的例子

JDK1.8 中list<bean>转为 Map<id,name>

Map<Integer, String> appleMap = appleList.stream().collect(Collectors.toMap(Apple::getId, Apple::getName );

读取文件

List<String> strs = Files.lines(Paths.get(fileName), Charset.defaultCharset()).collect(Collectors.toList());
或者
List<String> lineLists = Files
        .lines(Paths.get(fileName), Charset.defaultCharset())
        .flatMap(line -> Arrays.stream(line.split(",")))
        .collect(Collectors.toList());

 

 

一只叫狗的猫 发布了121 篇原创文章 · 获赞 40 · 访问量 1万+ 私信 关注

标签:toList,JDK1.8,stream,Collectors,元素,常用,语法,collect,asList
来源: https://blog.csdn.net/zgsxhdzxl/article/details/104605455

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有