[英]How to split list to multiple lists that have all the same elements
我有以下字符串列表
["a", "a", "b", "b", "b"]
我想创建包含重复多次的元素的列表,对于前面的例子来说
["a", "a"], ["b", "b", "b"]
我怎样才能在java中实现它?
编辑:元素可能不会在主列表中排序。
你可以做
list.stream().collect(Collectors.groupingBy(Function.identity())).values();
这是你想要的吗?
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());
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.