how to get unique items from the Arraylist, preserving the natural order

谁说我不能喝 提交于 2019-12-25 18:36:58

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!