[英]Converting a collection to Map by sorting it using java 8 streams
我有一個列表,我需要自定義排序,然后轉換為具有其Id與名稱映射的地圖。
這是我的代碼:
Map<Long, String> map = new LinkedHashMap<>();
list.stream().sorted(Comparator.comparing(Building::getName)).forEach(b-> map.put(b.getId(), b.getName()));
我認為這將完成這項工作,但我想知道我是否可以避免在這里創建LinkedHashMap
並使用花哨的函數式編程來完成一行中的工作。
你有Collectors.toMap
用於這個目的:
Map<Long, String> map =
list.stream()
.sorted(Comparator.comparing(Building::getName))
.collect(Collectors.toMap(Building::getId,Building::getName));
如果要強制實例化將要實例化的Map實現,請使用以下命令:
Map<Long, String> map =
list.stream()
.sorted(Comparator.comparing(Building::getName))
.collect(Collectors.toMap(Building::getId,
Building::getName,
(v1,v2)->v1,
LinkedHashMap::new));
使用java.util.stream.Collectors
toMap()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.