在日常工作中,我们时常会遇到需要对数据进行遍历去重的操作,笔者便将自己所熟知的几种方法分享给大家。
首先模拟一个实体类,并创建一个main方法调用。
public static void main(String[] args) {
List list = new ArrayList(4);
list.add(new User("张三","杭州"));
list.add(new User("李四","上海"));
list.add(new User("王五","深圳"));
list.add(new User("赵六","深圳"));
}
public class User{
private String name;
private String city;
public User(String name, String city) {
this.name = name;
this.city = city;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}
1.双重循环比较 思路:创建一个新的不重复列表 每次遍历元素都和之前存放的元素进行比较,若重复则移除,遍历一次后再放入。这也是初学者们最先运用到的一种方法。
public List duplicateRemovalByCircle(Listlist){ List newList = new ArrayList(); for (int i = 0;i < list.size();i++){ for (int j = 0;j < i;j++){ if(list.get(i).getCity().equals(list.get(j).getCity())){ newList.remove(list.get(j).getCity()); } } newList.add(list.get(i).getCity()); } return list; }
2.使用Set集合 思路:Set是元素不可重复的集合,遍历列表直接将元素放入Set集合即可完成去重,或者直接使用Set转换成List的方法 拓展:查看源码可知,HashSet的底层是HashMap,而HashSet的Add方法也就是调用了HashMap的put方法,Set的元素作为Map中的key,Object实例作为值。
public List duplicateRemovalBySet(Listlist){ Set set = new HashSet(); list.addAll(set); for(int i = 0;i < list.size();i++){ set.add(list.get(i).getCity()); } List newlist = new ArrayList(); newlist.addAll(set); return newlist; }
3.使用Java8的新特性 stream进行去重 思路:使用流操作集合,高效易懂,并且拓展性强。
public List duplicateRemovalByStream(Listlist){ List newList = new ArrayList(); newList = list.stream().map(User::getCity).distinct().collect(Collectors.toList()); return newList; }



