Получение значений из пары в HashMap за Java - PullRequest
1 голос
/ 11 марта 2020

У меня есть Map<Pair<String, String>, Integer> вот так:

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

Теперь, если я передам значение Pair.left как 1, тогда я должен получить 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

}

Есть ли какой-нибудь простой способ сделать это из лямбды?

Ответы [ 3 ]

0 голосов
/ 11 марта 2020

Вы можете выполнить операцию группировки, используя преобразование, например:

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())));
}
0 голосов
/ 11 марта 2020

Идея состоит в том, чтобы построить временную структуру данных, которая содержит левую позицию -> Карта (справа, целое число) и вернуть карту с заданным левым значением.

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);
}
0 голосов
/ 11 марта 2020

Вы пробовали что-то вроде:

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()));
}
...