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

How to group by objects in java using collections?

我是 Java 的新手,我正在尝试根据数量对对象进行分组,但我做不到。这是示例:

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

基本上,当数字相同时,需要将值分组到相同的数字下。这都是关于如何通过使用任何集合来执行这种战略输出来实现的。感谢任何帮助。

正如其他人所建议的,如果您只想坚持使用 JDK 集合,则可以使用 Map<Integer, List<Object>>

但是,可以免费为您完成所有工作的多值地图。尤其要检查这个问题 what java collection that provides multiple values for the same key (see the listing here )。

甚至有一个结构可以帮助您做到这一点。

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