【问题标题】:Getting values from pair to HashMap in Java在Java中从pair中获取值到HashMap
【发布时间】:2020-03-11 16:15:54
【问题描述】:

我有一个这样的Map<Pair<String, String>, Integer>

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

现在,如果我像 1 一样传递 Pair.left 值,那么我应该在地图中获得 Pair.right 和该整数:

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 有什么简单的方法可以做到这一点吗?

【问题讨论】:

  • 如果您只对基于 Pair.left 的值感兴趣,那么为什么要使用整个 Pair 类作为映射键?
  • 因为基于 Pair.left 我会知道要传递什么并且它已经在其他几个地方使用过。我需要在几个地方映射 pair.left 和 pair.right。

标签: java lambda java-8


【解决方案1】:

你有没有尝试过:

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

      想法是建立一个临时的数据结构来保存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);
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2010-11-25
        • 2016-03-08
        • 1970-01-01
        • 2020-07-15
        • 2011-03-26
        相关资源
        最近更新 更多