如何从Arraylist中获得唯一项,并保持自然顺序 [英] how to get unique items from the Arraylist, preserving the natural order

查看:149
本文介绍了如何从Arraylist中获得唯一项,并保持自然顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如ArrayList:

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和6被删除,因为它们多次出现.

0, 3 and 6 are removed because they occur more than once.

推荐答案

将元素放入LinkedHashSet;如果找到已经存在的元素,则将其放入另一个集合;最后删除所有已经存在"的元素:

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演示

这篇关于如何从Arraylist中获得唯一项,并保持自然顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆