Java哈希映射过滤

Java哈希映射过滤,java,hashmap,treemap,Java,Hashmap,Treemap,我有一个hashmap数据 {1={Context=Legacy, Owner=Ram, Number=xyz}, 2={Context=Legacy, Owner=Ram, Number=xxx}, 3={Context=Legacy, Owner=Sri, Number=xrt}} 我如何过滤掉这个Hashmap,它有包含Owner=Ram的映射 预期结果: {1={Context=Legacy, Owner=Ram, Number=xyz}, 2={Context=Legacy, Ow

我有一个hashmap数据

{1={Context=Legacy, Owner=Ram, Number=xyz}, 2={Context=Legacy, Owner=Ram,
 Number=xxx}, 3={Context=Legacy, Owner=Sri, Number=xrt}}
我如何过滤掉这个Hashmap,它有包含Owner=Ram的映射

预期结果:

{1={Context=Legacy, Owner=Ram, Number=xyz}, 2={Context=Legacy, Owner=Ram, Number=xxx}}

如果您碰巧使用Java 8,则可以通过使用和来实现:


这两者都将删除所有拥有所有者的条目!=Ram。

如果您使用的是java8或更高版本

// If you have setup like this
Map<Integer, Map<String, String>> m = new HashMap<>();
Map<String, String> c1 = new HashMap<>();
c1.put("Context", "Legacy");
c1.put("Owner", "Ram");
c1.put("Number", "xyz");
m.put(1, c1);
Map<String, String> c2 = new HashMap<>();
c2.put("Context", "Legacy");
c2.put("Owner", "NotRam");
c2.put("Number", "xyz");
m.put(2, c2);

// you can do like this.
Map result = m.entrySet().stream()
            .filter(x -> x.getValue().entrySet().stream()
                    .anyMatch(y -> y.getKey().equals("Owner") && y.getValue().equals("Ram")))
            .collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue()));

System.out.println(result);

哪个版本的Java?你尝试了什么?我在google上快速查看了一下,你可以看到Java 8之前和之后的过滤版本:我的问题得到了回答。非常感谢你的建议。真的很有帮助。
Map<Integer, MyCustomObject> map = ...;
for(Iterator<MyCustomObject> iter = map.values().iterator(); iter.next();){
    if(!iter.next().getOwner().equals("Ram")){
        iter.remove();
    }
}
// If you have setup like this
Map<Integer, Map<String, String>> m = new HashMap<>();
Map<String, String> c1 = new HashMap<>();
c1.put("Context", "Legacy");
c1.put("Owner", "Ram");
c1.put("Number", "xyz");
m.put(1, c1);
Map<String, String> c2 = new HashMap<>();
c2.put("Context", "Legacy");
c2.put("Owner", "NotRam");
c2.put("Number", "xyz");
m.put(2, c2);

// you can do like this.
Map result = m.entrySet().stream()
            .filter(x -> x.getValue().entrySet().stream()
                    .anyMatch(y -> y.getKey().equals("Owner") && y.getValue().equals("Ram")))
            .collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue()));

System.out.println(result);