Vip*_*han 0 java collections android arraylist
我有一个arraylist包含一些重复的值我想将这些值收集到另一个Arraylist ....喜欢
Arraylist<String> one; //contains all values with duplicates
one.add("1");
one.add("2");
one.add("2");
one.add("2");
Run Code Online (Sandbox Code Playgroud)
在这里,我想在另一个arraylist中获取所有重复值...
Arraylist<String> duplicates; //contains all duplicates values which is 2.
Run Code Online (Sandbox Code Playgroud)
我想要那些数量大于或等于3的值......
目前,我没有任何解决方案,请帮助我找出答案
您可以使用一组:
Set<String> set = new HashSet<>();
List<String> duplicates = new ArrayList<>();
for(String s: one) {
if (!set.add(s)) {
duplicates.add(s);
}
}
Run Code Online (Sandbox Code Playgroud)
您只需将所有元素添加到集合中即可.如果method add()返回false,则表示元素未添加到set,即它已经存在.
输入: [1, 3, 1, 3, 7, 6]
重复: [1, 3]
EDITED
对于计数为3或更大的值,您可以使用流来执行此操作:
List<String> collect = one.stream()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
.entrySet()
.stream()
.filter(e -> e.getValue() >= 3)
.map(Map.Entry::getKey)
.collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)
基本上你在地图中收集初始列表,key字符串在哪里,value是计数.然后,您可以过滤此映射以查找计数大于3的值,并将其收集到结果列表中
| 归档时间: |
|
| 查看次数: |
97 次 |
| 最近记录: |