问题
I have an arraylist which contains some values with duplicates i want to collect those values into another Arraylist.... like
Arraylist<String> one; //contains all values with duplicates
one.add("1");
one.add("2");
one.add("2");
one.add("2");
Here, I want to get all the duplicates values in another arraylist...
Arraylist<String> duplicates; //contains all duplicates values which is 2.
I want those values which counts greater or equals 3.....
Currently, I don't have any solution for this please help me to find out
回答1:
You can use a set for this:
Set<String> set = new HashSet<>();
List<String> duplicates = new ArrayList<>();
for(String s: one) {
if (!set.add(s)) {
duplicates.add(s);
}
}
You just keep adding all the elements to the set. If method add()
returns false, this means the element was not added to set i.e it already exists there.
Input: [1, 3, 1, 3, 7, 6]
duplicates: [1, 3]
EDITED
For the value which counts 3 or greater, you can use streams to do it like so:
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());
Basically you collect you initial list in a map, where key
is the string and value
is the count. Then you filter this map for values that have count greater than 3, and collect it to the result list
回答2:
You could also do this via a stream:
List<String> duplicates = one.stream()
.collect(Collectors.groupingBy(Function.identity(), counting()))
.entrySet()
.stream()
.filter(e -> e.getValue() > 1)
.map(Map.Entry::getKey)
.collect(Collectors.toCollection(ArrayList::new));
来源:https://stackoverflow.com/questions/54007206/get-the-duplicates-values-from-arrayliststring-and-then-get-those-items-in-ano