如何将列表拆分为具有相同元素的多个子列表。

huangapple go评论68阅读模式
英文:

How to split list to multiple lists that have all the same elements

问题

我有以下的字符串列表

["a", "a", "b", "b", "b"]

我想创建包含重复出现超过一次的元素的子列表,对于前面的例子,结果应该是

["a", "a"], ["b", "b", "b"]

我该如何在Java中实现这个功能?

编辑:
主列表中的元素可能无序。

英文:

I have the following list of String

["a", "a", "b", "b", "b"]

I want to create lists that have elements that repeat themselves more than once, for the previous example that would be

["a", "a"], ["b", "b", "b"]

How can I achieve that in java?

EDIT:
elements may not be ordered in primary list.

答案1

得分: 1

你可以这样做:

list.stream().collect(Collectors.groupingBy(Function.identity())).values();
英文:

You can do

list.stream().collect(Collectors.groupingBy(Function.identity())).values();

答案2

得分: 0

以下是您要翻译的代码部分:

private void splitDuplicateList(String[] arr) {
    Map<String, Integer> map = new HashMap<>();
    for (String item : arr) {
        if (!map.containsKey(item)) {
            map.put(item, 1);
        } else {
            map.put(item, map.get(item) + 1);
        }
    }
    for (Map.Entry entry : map.entrySet()) {
        List<String> list = new ArrayList<>();
        for (int count = 0; count < (int) entry.getValue(); count++) {
            list.add((String) entry.getKey());
        }
        System.out.println(list.toString());
    }
}
英文:

Is this what you want?

private void splitDuplicateList(String[] arr) {
    Map&lt;String, Integer&gt; map = new HashMap&lt;&gt;();
    for (String item : arr) {
        if (!map.containsKey(item)) {
            map.put(item, 1);
        } else {
            map.put(item, map.get(item) + 1);
        }
    }
    for (Map.Entry entry : map.entrySet()) {
        List&lt;String&gt; list = new ArrayList&lt;&gt;();
        for (int count = 0; count &lt; (int) entry.getValue(); count++) {
            list.add((String) entry.getKey());
        }
        System.out.println(list.toString());
    }
}

huangapple
  • 本文由 发表于 2020年9月29日 17:56:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/64117207.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定