在Java中获取从对到HashMap的值



我有一个Map<Pair<String, String>, Integer>,如下所示:

Pair.left Pair.right Integer
1          A          10
1          B          20
2          C          30

现在,如果我传递像1这样的Pair.left值,那么我应该在像这样的映射中获得Pair.right和那个Integer

Map<String, Integer> :
A  10
B  20
If i pass 2, 
then 
C 30

所以,我试试这个:

public Map<String, Integr> foo(Map<Pair<String, String>, Integer> input, String LeftValue)
{
Map<String, Integer> result = new HashMap();
Set<Pair<String, String>> inputKeysets = input.keySet();
//Now, I am thinking i will loop through the inputKeysets and see if the getLeft() matches the LeftValue, if it does then i will take the getRight() and store in a new Set
//Then i will have LeftValue and RightValue and then will compare again from the input and get the Integer value
}

从lambda有什么简单的方法可以做到这一点吗?

你有没有尝试过这样的东西:

public Map<String, Integer> foo(Map<Pair<String, String>, Integer> input, String leftValue) {
return input.entrySet().stream()
.filter(e -> e.getKey().left.equals(leftValue))
.collect(Collectors.toMap(e -> e.getKey().right, e -> e.getValue()));
}

您可以使用映射下游进行分组操作,例如:

public Map<String, List<Pair<String, Integer>>> groupedByLeft(Map<Pair<String, String>, Integer> input) {
return input.entrySet().stream()
.collect(Collectors.groupingBy(e -> e.getKey().getLeft(),
Collectors.mapping(e -> Pair.of(e.getKey().getRight(), e.getValue()),
Collectors.toList())));
}

想法是建立一个临时数据结构,保存left->Map(right,integer(,并返回一个给定left值的Map。

public Map<String, Integer> foo(Map<Pair<String, String>, Integer> input, String LeftValue) {
Map<String, Integer> result = new HashMap();
Set<Pair<String, String>> inputKeysets = input.keySet();
Map<String, Map<String, Integer>> tempDS = new HashMap<>();
for (Pair<String, String> pair : inputKeysets) {
String left = pair.getKey();
String right = pair.getValue();
int value = input.get(pair);
if (tempDS.containsKey(left)) {
tempDS.get(left).put(right, value);
} else {
Map<String, Integer> temp = new HashMap<>();
temp.put(right, value);
tempDS.put(left, temp);
}
}
return tempDS.get(LeftValue);
}

最新更新