-1

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.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243
Oleg
  • 45
  • 7
  • 2
    Please show some code. What have you tried? ("Natural order" is the order of the counting numbers (in this case). -4 should come first. I assume you mean the order given in the list.) – markspace Oct 27 '17 at 19:03
  • 1
    @JBNizet because there's more than one occurrence of those. – Andy Turner Oct 27 '17 at 19:05
  • Ah, OK. Please clarify that in your question. – JB Nizet Oct 27 '17 at 19:06
  • @markspace First I wanted with a hashmap, if the element was added (it's unique) then add it to the new list. But the expression does not take the boolean expression – Oleg Oct 27 '17 at 19:09
  • This is not a duplicate of [How do I remove repeated elements from ArrayList?](https://stackoverflow.com/questions/203984/how-do-i-remove-repeated-elements-from-arraylist). The answers there leave elements which are duplicated, but just one occurrence of them. This question is asking how to find elements which occur *exactly once*. – Andy Turner Oct 28 '17 at 13:43

2 Answers2

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

Andy Turner
  • 137,514
  • 11
  • 162
  • 243
1

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());
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255