[英]Collect stream of EntrySet to LinkedHashMap
I want to collect the stream to a LinkedHashMap<String, Object>
. 我想将流收集到
LinkedHashMap<String, Object>
。
I have a JSON
resource that is stored in LinkedHashMap<String, Object> resources
. 我有一个存储在
LinkedHashMap<String, Object> resources
的JSON
LinkedHashMap<String, Object> resources
。 Then I filter out JSON
elements by streaming the EntrySet
of this map. 然后我通过流式传输此地图的
EntrySet
来过滤掉JSON
元素。 Currently I am collecting the elements of stream to a regular HashMap
. 目前我正在将流的元素收集到常规
HashMap
。 But after this I am adding other elements to the map. 但在此之后我将其他元素添加到地图中。 I want these elements to be in the inserted order.
我希望这些元素处于插入顺序。
final List<String> keys = Arrays.asList("status", "createdDate");
Map<String, Object> result = resources.entrySet()
.stream()
.filter(e -> keys.contains(e.getKey()))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
result.put("date", "someDate");
return result;
That is why I want to collect the stream to a LinkedHashMap<String, Object>
. 这就是我想要将流收集到
LinkedHashMap<String, Object>
。 How can I achieve this? 我怎样才能做到这一点?
You can do this with Stream
: 你可以用
Stream
做到这一点:
Map<String, Object> result = resources.entrySet()
.stream()
.filter(e -> keys.contains(e.getKey()))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (x, y) -> y, LinkedHashMap::new));
The part (x, y) -> y
is because of mergeFunction when find duplicate keys, it returns value of second key which found. 部分
(x, y) -> y
是因为mergeFunction找到重复键时,它返回找到的第二个键的值。 the forth part is mapFactory which a supplier providing a new empty Map into which the results will be inserted. 第四部分是mapFactory ,供应商提供一个新的空Map,结果将插入其中。
An alternate way of doing this using Map.forEach
is: 使用
Map.forEach
执行此操作的另一种方法是:
Map<String, Object> result = new LinkedHashMap<>();
resources.forEach((key, value) -> {
if (keys.contains(key)) {
result.put(key, value);
}
});
result.put("date", "someDate");
and if you could consider iterating on the keySet
as an option: 如果你可以考虑迭代
keySet
作为一个选项:
Map<String, Object> result = new LinkedHashMap<>();
resources.keySet().stream()
.filter(keys::contains)
.forEach(key -> result.put(key,resources.get(key)));
result.put("date", "someDate");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.