Java 如何在流式传输(lambda)时删除 HashMap 的元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23808973/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to remove an element of a HashMap whilst streaming (lambda)
提问by Dan
I have the following situation where I need to remove an element from a stream.
我有以下情况,我需要从流中删除一个元素。
map.entrySet().stream().filter(t -> t.getValue().equals("0")).
forEach(t -> map.remove(t.getKey()));
in pre Java 8 code one would remove from the iterator - what's the best way to deal with this situation here?
在 Java 8 之前的代码中,一个将从迭代器中删除 - 在这里处理这种情况的最佳方法是什么?
采纳答案by Louis Wasserman
map.entrySet().removeIf(entry -> entry.getValue().equals("0"));
You can't do it with streams, but you can do it with the other new methods.
你不能用流来做,但你可以用其他新方法来做。
EDIT: even better:
编辑:甚至更好:
map.values().removeAll(Collections.singleton("0"));
回答by maczikasz
I think it's not possible (or deffinitelly shouldn't be done) due to Streams' desire to have Non-iterference, as described here
我认为这是不可能的(或deffinitelly不应该做的),由于流有非iterference欲望,如所描述这里
If you think about streams as your functional programming constructs leaked into Java, then think about the objects that support them as their Functional counterparts and in functional programming you operate on immutable objects
如果您将流视为泄漏到 Java 中的函数式编程构造,那么将支持它们的对象视为它们的函数式对应物,并且在函数式编程中您对不可变对象进行操作
And for the best way to deal with this is to use filter just like you did
处理这个问题的最好方法是像你一样使用过滤器
回答by abhi169jais
If you want to remove the entire key, then use:
如果要删除整个密钥,请使用:
myMap.entrySet().removeIf(map -> map.getValue().containsValue("0"));
回答by Cyberpunk
1st time replying. Ran across this thread and thought to update if others are searching. Using streams you can return a filtered map<> or whatever you like really.
第一次回复。浏览此线程并考虑在其他人正在搜索时进行更新。使用流,您可以返回过滤后的 map<> 或您真正喜欢的任何内容。
@Test
public void test() {
Map<String,String> map1 = new HashMap<>();
map1.put("dan", "good");
map1.put("Jess", "Good");
map1.put("Jaxon", "Bad");
map1.put("Maggie", "Great");
map1.put("Allie", "Bad");
System.out.println("\nFilter on key ...");
Map<String,String> map2 = map1.entrySet().stream().filter(x ->
x.getKey().startsWith("J"))
.collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue()));
map2.entrySet()
.forEach(s -> System.out.println(s));
System.out.println("\nFilter on value ...");
map1.entrySet().stream()
.filter(x -> !x.getValue().equalsIgnoreCase("bad"))
.collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue()))
.entrySet().stream()
.forEach(s -> System.out.println(s));
}
------- output -------
Filter on key ...
Jaxon=Bad
Jess=Good
Filter on value ...
dan=good
Jess=Good
Maggie=Great