集合去掉重复元素
1、字符串去重
public static void main(String[] args) {
//集合去重
List<String> list = new ArrayList<String>();
list.add("张三");
list.add("李四");
list.add("王五");
list.add("赵六");
list.add("王五");
list.add("张三");
//定义一个set集合
Set<String> set = new HashSet<String>();
//遍历list集合,将list集合中的元素添加到set集合中
for (String str : list) {
set.add(str);
}
for (String s : set) {
System.out.println("s的值为:"+s);
}
}
2、对象去重
package com.myproj.pojo;
public class People {
private String name;
private int age;
private String sex;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public People() {
super();
}
public People(String name, int age, String sex) {
super();
this.name = name;
this.age = age;
this.sex = sex;
}
@Override
public String toString() {
return "People [name=" + name + ", age=" + age + ", sex=" + sex + "]";
}
//重写hashcode和equals方法
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + age;
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((sex == null) ? 0 : sex.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
People other = (People) obj;
if (age != other.age)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (sex == null) {
if (other.sex != null)
return false;
} else if (!sex.equals(other.sex))
return false;
return true;
}
}
public static void main(String[] args) {
//创建一个装载people对象的list集合
List<People> list = new ArrayList<People>();
//向list集合中添加元素(我直接添加了)
list.add(new People("白月初",12,"男"));
list.add(new People("涂山苏苏",10,"女"));
list.add(new People("涂山雅雅",21,"女"));
list.add(new People("东方月初",22,"男"));
list.add(new People("白月初",12,"男"));
list.add(new People("涂山苏苏",10,"女"));
list.add(new People("王权富贵",22,"男"));
for (People people : list) {
System.out.println(people);
}
System.out.println("***************添加到set集合之前list中的people******************");
Set<People> set = new HashSet<People>();
for (People people : list) {
set.add(people);
}
System.out.println("***************添加到set集合之后******************");
for (People people : set) {
System.out.println(people);
}
}
//注意一定要在实体类中重写hashcode方法和equals方法set方法才会达到去重的效果,
在这里要注意的是:list是有序可重复的集合,而set是无序且不可以存重复元素的集合,但是对于对象来说,区分是否为同一个对象,要注意它的hashcode。
3.对于有主键的对象来说,去重时,可以根据主键是唯一的特点去重。