java check for 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());

Tags:

Java Example