简体   繁体   English

如何使用集合在java中按对象分组?

[英]How to group by objects in java using collections?

I'm very new to Java and I am trying to group by objects based on the number but I'm unable to make it.我对 Java 很陌生,我试图根据数字按对象进行分组,但我无法做到。 Here is the example:这是示例:

SomeCollection<Integer,String> t=new SomeCollection<Integer,String>();
t.put("1","a");
t.put("1","b");
t.put("2","c");

output:
1 - a,b
2 - c

Basically, when numbers are same then value needs to be grouped under that same number.基本上,当数字相同时,值需要分组在相同的数字下。 It's all about asking how to perform this kind of strategical output to achieve by using any collections.这完全是关于询问如何通过使用任何集合来实现这种战略输出。 Any help is appreciated.任何帮助表示赞赏。

As suggested by others, you can use a Map<Integer, List<Object>> if you want to stick only to JDK collections.正如其他人所建议的那样,如果您只想坚持使用 JDK 集合,则可以使用Map<Integer, List<Object>>

However, there are Multi Value Maps out there which will do all the work for you for free.但是,有多值地图可以免费为您完成所有工作。 Check out this question what java collection that provides multiple values for the same key (see the listing here https://stackoverflow.com/a/22234446/3114959 in particular).看看这个问题是什么java集合为同一个键提供了多个值(特别是参见这里的列表https://stackoverflow.com/a/22234446/3114959 )。

    Map<String, Integer> map = new HashMap<>();
    map.put("a", 1);
    map.put("b", 1);
    map.put("c", 2);
    map.put("d", 1);
    map.put("e", 3);
    map.put("f", 3);
    map.put("g", 3);

    //Using Java 7
    Set<Integer> set = new HashSet<Integer>();
    Map<Integer, List<String>> finalList = new HashMap<Integer, List<String>>();
    for (Map.Entry<String, Integer> entry : map.entrySet()) {
        set.add(entry.getValue());
        finalList.put(entry.getValue(), new ArrayList<String>());
    }
    for (Map.Entry<String, Integer> entry : map.entrySet()) {
        for (Integer value : set) {
            if (value.equals(entry.getValue())) {
                List<String> values = finalList.get(value);
                values.add(entry.getKey());
            }
        }
    }
    System.out.println("Result : " + finalList.toString());

There is even a construct which will help you do this.甚至有一个结构可以帮助你做到这一点。

Map<String, Integer> map = new HashMap<>();
map.put("a", 1);
map.put("b", 1);
map.put("c", 2);

Map<Integer, List<String>> groupedMap = map.keySet().stream()
        .collect(Collectors.groupingBy(map::get));

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

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