java check duplicates in list code example
Example 1: java array check duplicates
duplicates = false;
for(i = 0; i < zipcodeList.length; i++) {
for(j = i + 1; k < zipcodeList.length; j++) {
if(j != i && zipcodeList[j] == zipcodeList[i]) {
duplicates = true;
}
}
}
Example 2: java 8 get duplicates in list
List<Integer> numbers = Arrays.asList(1, 2, 1, 3, 4, 4);
Set<Integer> nbrRemovedSet = new HashSet<>();
// Set.add() returns false if the element was already in the set.
Set<Integer> nbrSet = numbers
.stream()
.filter(n -> !nbrRemovedSet.add(n))
.collect(Collectors.toSet());
// also, we can use Collections.frequency:
Set<Integer> nbrSet = numbers
.stream()
.filter(i -> Collections.frequency(numbers, i) >1)
collect(Collectors.toSet());
Example 3: find repeated elements in array java
for (String name : names) {
if (set.add(name) == false) {
// your duplicate element
}
}
Example 4: java find duplicates in array
// Uses a set, which does not allow duplicates
for (String name : names)
{
if (set.add(name) == false)
{
// print name your duplicate element
}
}