我有一个Map地图,需要使用lambda表达式基于另一个Map进行过滤
我试图在地图上进行过滤,并找到基于另一张地图的所有匹配项,但它似乎不起作用。似乎值未正确过滤。 有什么方法可以执行流和映射并将过滤逻辑放置在那里? 有人可以帮忙吗
public static void main(String []args){
System.out.println("Hello World");
Map<String,List<String>> items = new HashMap<>();
List<String> ut1=new ArrayList<>();
ut1.add("S");
ut1.add("C");
List<String> ut2=new ArrayList<>();
ut2.add("M");
List<String> ut3=new ArrayList<>();
ut3.add("M");
ut3.add("C");
items .put("1010016",ut1);
items .put("1010019",ut2);
items .put("1010012",ut3);
System.out.println("Map"+items);
Map<String,Map<String,String>> sKey = new HashMap<>();
Map<String,String> utKey1 = new HashMap<>();
utKey1.put("S","1001");
utKey1.put("M","1002");
utKey1.put("C","1003");
Map<String,String> utKey2 = new HashMap<>();
utKey2.put("S","1004");
Map<String,String> utKey3 = new HashMap<>();
utKey3.put("S","1005");
utKey3.put("M","1006");
Map<String,String> utKey4 = new HashMap<>();
utKey4.put("S","1007");
utKey4.put("M","1008");
utKey4.put("C","1009");
sKey.put("1010016",utKey1);
sKey.put("1010019",utKey2);
sKey.put("1010012",utKey3);
sKey.put("1010011",utKey4);
System.out.println("Map2"+sKey);
Map<String,Map<String,String>> map3 =
sKey.entrySet().stream()
.filter(x ->
items.containsKey(x.getKey())
&& x.getValue().entrySet().stream().allMatch(y ->
items.entrySet().stream().anyMatch(list ->
list.getValue().contains(y.getKey()))))
.collect(Collectors.toMap(Entry::getKey, Entry::getValue));
System.out.println("Map3"+map3);
}
过滤后的地图返回为:
Map3 {1010012 = {S = 1005,M = 1006},1010016 = {S = 1001,C = 1003,M = 1002},1010019 = {S = 1004}}
但是实际结果应该是:
Map3 {1010012 = {M = 1006},1010016 = {S = 1001,C = 1003}}
答案 0 :(得分:0)
我宁愿说这是一种解决方法,可以使用流实现预期的输出。
Map<String, Map<String, String>> result =
sKey.entrySet().stream()
.filter(detail -> items.keySet().contains(detail.getKey()) &&
!Collections.disjoint(detail.getValue().keySet(), items.get(detail.getKey())))
.collect(HashMap::new,
(m,v) -> m.put(v.getKey(), v.getValue().entrySet().stream()
.filter(detail -> items.get(v.getKey()).contains(detail.getKey()))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue))),
HashMap::putAll);
输出
{1010012={M=1006}, 1010016={S=1001, C=1003}}