创建一个流以根据两个地图的值相交

时间:2019-05-05 14:00:30

标签: java java-8 java-stream

我有一个名为getNames的方法。其目标是:返回两个地图中都出现的名称。我尝试将此方法重写为Stream。但是,我不希望在此操作中修改testOneNames。如何将其重建为流?

private Map<String, List<String>> getNames(Map<String, List<String>> testOneNames, Map<String, List<String>> testSecondNames) {
    Map<String, List<String>> copyTestOneName = new HashMap<>(testOneNames);
    copyTestOneName.values().retainAll(testSecondNames.values());
    return copyTestOneName;
}

1 个答案:

答案 0 :(得分:0)

您可以执行以下操作:

private Map<String, List<String>> getNames(Map<String, List<String>> testOneNames, Map<String, List<String>> testSecondNames) {
    return testOneNames.entrySet().stream().filter(e -> testSecondNames.containsValue(e.getValue())).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
}