For example my list contains {4, 6, 6, 7, 7, 8} and I want final result = {6, 6, 7, 7}
One way is to loop through the list and eliminate unique values (4, 8 in this
Your List
should ideally have been a Set
which doesn't allow duplicates in the first place. As an alternative to looping, you could either convert and switch to Set
or use it intermediately to eliminate duplicates as follows:
List dupesList = Arrays.asList(4L, 6L, 6L, 7L, 7L, 8L);
Set noDupesSet = new HashSet(dupesList);
System.out.println(noDupesSet); // prints: [4, 6, 7, 8]
// To convert back to List
Long[] noDupesArr = noDupesSet.toArray(new Long[noDupesSet.size()]);
List noDupesList = Arrays.asList(noDupesArr);
System.out.println(noDupesList); // prints: [4, 6, 7, 8]