![](/img/trans.png)
[英]How to use Java regex or Java streams for the given string pattern and create a map out of it
[英]How to use Java streams to create a list out of a map site
從 map 開始,例如:
Map<Integer, String> mapList = new HashMap<>();
mapList.put(2,"b");
mapList.put(4,"d");
mapList.put(3,"c");
mapList.put(5,"e");
mapList.put(1,"a");
mapList.put(6,"f");
我可以使用以下流對 map 進行排序:
mapList.entrySet()
.stream()
.sorted(Map.Entry.<Integer, String>comparingByKey())
.forEach(System.out::println);
但是我需要獲取與鍵對應的對應排序元素的列表(和字符串)(即:ab c def):1 2 3 4 5 6。
我在 Stream 命令中找不到方法。
謝謝
正如@MA 在他的評論中所說,我需要一個映射,這在這個問題中沒有解釋: How to convert a Map to List in Java?
所以非常感謝@MA
有時人們太快結束問題了!
您可以使用映射收集器:
var sortedValues = mapList.entrySet()
.stream()
.sorted(Map.Entry.comparingByKey())
.collect(Collectors.mapping(Entry::getValue, Collectors.toList()))
您還可以使用一些不同的集合類而不是流:
List<String> list = new ArrayList<>(new TreeMap<>(mapList).values());
不利的一面是,如果您在一行中完成所有這些操作,它會變得非常混亂,非常快。 此外,您只是為了排序而丟棄了中間TreeMap
。
如果要對鍵進行排序並僅收集值,則需要使用映射 function 僅在排序后保留值。 之后,您可以收集或執行 foreach 循環。
mapList.entrySet()
.stream()
.sorted(Map.Entry.comparingByKey())
.map(Map.Entry::getValue)
.collect(Collectors.toList());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.