问题
For example ArrayList :
Integer[] intArray = new Integer[] { 0, 1 , 0 , 2 , 3 , 3 , 5 , 6 , -4 ,6 };
ArrayList<Integer> list = new ArrayList<Integer>(Arrays.asList(intArray));
need to get non-repeating values, preserving order
1 , 2 , 5 , -4
0, 3 and 6 are removed because they occur more than once.
回答1:
Put the elements into a LinkedHashSet
; if you find an element that's already present, put it into another set; remove all the "already present" elements at the end:
LinkedHashSet<Integer> set = new LinkedHashSet<>();
HashSet<Integer> alreadyPresent = new HashSet<>();
for (Integer i : intArray) {
if (!set.add(i)) {
alreadyPresent.add(i);
}
}
set.removeAll(alreadyPresent);
ArrayList<Integer> list = new ArrayList<>(set);
Ideone demo
回答2:
Other solution: build a histogram of all numbers (i.e. number of occurrences of each number), and only keep the numbers whose occurrences is 1.
With streams:
List<Integer> result =
list.stream()
.collect(Collectors.toMap(Function.identity(), i -> 1, Integer::sum, LinkedHashMap::new))
.entrySet()
.stream()
.filter(e -> e.getValue() == 1)
.map(Map.Entry::getKey)
.collect(Collectors.toList());
来源:https://stackoverflow.com/questions/46981793/how-to-get-unique-items-from-the-arraylist-preserving-the-natural-order