一点一滴记录 Java 8 stream 的使用

日常用到,一点一滴记录,不断丰富,知识积累,塑造自身价值。欢迎收藏

String 转 List

String str = "1,2,3,4";
List<Long> lists = Arrays.stream(str.split(",")).map(s -> Long.parseLong(s.trim())).collect(Collectors.toList());

List 转 String

list.stream().map(String::valueOf).collect(Collectors.joining(","))

List<> 对象获取某个值 转为 list<Long>

List<itemsBeans> = new ArrayList();
List<Long> items = itemsBeans.stream().map(ItemsBean::getItemid).collect(Collectors.toList());

Set 转 List

Set<Long> sets = xxx
List<Long> hids =  sets.stream().collect(Collectors.toList());

List 转 Map<Long, String>

List<Hosts> hosts = xxxx
Map<Long, String> hostMap = hosts.stream().collect(Collectors.toMap(Hosts::getHostid,Hosts::getName, (k1, k2) -> k2));

 List 转 Map<Long, Object>

List<ItemTriggerGroupByName> hosts = xxxx
Map<Long, ItemTriggerGroupByName> appsMap= apps.stream().collect(Collectors.toMap(ItemTriggerGroupByName::getHostId, e -> e , (k1, k2) -> k2));

 List 分组 转 Map<Long, List<Object>>

Map<Integer, List<Apple>> groupBy = appleList.stream().collect(Collectors.groupingBy(Apple::getId));

List<Map<String,Object>> 转 Map<String,Object>

List<Map<String, Object>> ma = xxx

Map<String, Object> mapResource = ma.stream().map(Map::entrySet).flatMap(Set::stream).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (v1, v2) -> v2));

转化 再改变 key 
ma.stream().map(Map::entrySet).flatMap(Set::stream).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (v1, v2) -> { return v1 + "," + v2; }))

List 求和,最小,最大值,平均值获取

单数组类型

List<int> strs = Arrays.asList(34,5,1,76,23);
最小值
strs .stream().min(Comparator.comparing(Function.identity())).get();
最大值
strs .stream().max(Comparator.comparing(Function.identity())).get();


对象数组类型
int sum = empList.stream().mapToInt(Employee::getAge()).sum();
int max = empList.stream().mapToInt(Employee::getAge()).max().getAsInt();
int min = empList.stream().mapToInt(Employee::getAge()).min().getAsInt();
double avg = empList.stream().mapToInt(Employee::getAge()).average().getAsDouble();
System.out.println("最大值:"+max+"\n最小值:"+min+"\n总和:"+sum+"\n平均值:"+avg);

 

 

 

发布了45 篇原创文章 · 获赞 345 · 访问量 90万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 编程工作室 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览