一點一滴記錄 Java 8 stream 的使用

藍緣發表於2020-01-11

日常用到,一點一滴記錄,不斷豐富,知識積累,塑造自身價值。歡迎收藏

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

 

 

 

相關文章