一点一滴记录 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 = 

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);

扫描二维码关注公众号,回复: 8491766 查看本文章
发布了45 篇原创文章 · 获赞 344 · 访问量 90万+

猜你喜欢

转载自blog.csdn.net/mmm333zzz/article/details/103123058