繁体   English   中英

如何将数据保留在哈希图中

[英]How to keep data in a hash map

我可以打印如下数据:

id    comes_in
___   ________
1       1
2       1
3       1
4       2
5       2
6       3

id和comes_in都是整数,现在我想将其保存在hashmap中,其中key是comes_in,值是id的数组列表。

HashMap<Integer,ArrayList<Integer>> map=new  HashMap<Integer,ArrayList<Integer>>();

因此如下所示:

comes_in     id
________     ___
1             1,2,3 
2             4,5
3             6

但是问题是如何将它们放入哈希图中,因为最初我无法通过comes_in对ID进行分组。

使用Java 8 Stream。 您的任务可以轻松实现。 请参阅: https : //docs.oracle.com/javase/8/docs/api/java/util/stream/Collectors.html#groupingBy-java.util.function.Function-java.util.function.Supplier-java。 util.stream.Collector-

public class TestProgram {
  public static void main(String...args) {
    Map<Integer, Integer> map = new HashMap<>();
    map.put(1, 1);
    map.put(2, 1);
    map.put(3, 1);
    map.put(4, 2);
    map.put(5, 2);
    map.put(6, 3);

    Map<Object, List<Object>> result = map.entrySet().stream()
        .collect(Collectors.groupingBy(
              Entry::getValue, 
              HashMap::new, 
              Collectors.mapping(Entry::getKey, Collectors.toList())
            ));
    System.out.println(result);
    // {1=[1, 2, 3], 2=[4, 5], 3=[6]}
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM