I would like to sort a map in Java 8 using Stream by key but the order is defined in ordered set.
Key to order by:
LinkedHashSet<String> keysToOrderBy = new LinkedHashSet<String>();
keysToOrderBy.add("b");
keysToOrderBy.add("c");
keysToOrderBy.add("d");
keysToOrderBy.add("a");
keysToOrderBy.add("e");
The map:
Map<String, Object> map = new Map<String, Object>();
map.put("a",...);
map.put("b",...);
map.put("c",...);
The stream sort using parallel defaults:
LinkedHashMap<String, Object> ordered =
map.entrySet()
.stream()
.parallel()
.sorted(Map.Entry.comparingByKey())
.collect(Collectors.toMap(
Map.Entry::getKey,
Map.Entry::getValue,
(v1, v2) -> v1,
LinkedHashMap::new
));
The order of the new Map should be:
"b"
"c"
"d"
"a"
"e"
I assume I have to use a custom comparator?
You don't necessarily have to use a custom comparator; you just iterate over the sorted elements instead of the unsorted elements.
LinkedHashMap<String, Object> ordered = keysToOrderBy.stream()
.filter(map::containsKey)
.collect(Collectors.toMap(
e -> e,
map::get,
(v1, v2) -> v1, LinkedHashMap::new));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.