英文:
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<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());
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论