- 实体PersionInfo类
public class PersionInfo {
private String name;
private String sex;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public PersionInfo(String name,String sex,int age) {
this.name=name;
this.sex=sex;
this.age=age;
}
@Override
public String toString() {
return "PersionInfo [name=" + name + ", sex=" + sex + ", age=" + age
+ "]";
}
}
- 定义原始数据赋值
/**
* @author Administrator
*
* java去除list重复值(循环元素删除、通过HashSet删除)
*
* 对象重复是指对象里面的变量的值都相等,并不定是地址。list集合存储的类型是基础类型还比较好办,直接把list集合转换成set集合就会自动去除。
* 当set集合存储的是对象类型时,需要在对象的实体类里面重写public boolean equals(Object obj) {} 和 public int hashCode() {} 两个方法。
*
*/
public class MainActivity extends Activity {
List<PersionInfo> lists=new ArrayList<PersionInfo>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
PersionInfo info=new PersionInfo("IMCC消化科病房", "消化科", 13);
PersionInfo info1=new PersionInfo("IMCC消化科病房", "消化科",13);
PersionInfo info2=new PersionInfo("消化科病房", "消化内科科", 14);
PersionInfo info3=new PersionInfo("消化科病房(南院", "消化科", 15);
lists.add(info);
lists.add(info1);
lists.add(info2);
lists.add(info3);
remove(lists);
}
/**
*
* 去重
*/
private void remove(List<PersionInfo> lists){
HashSet<NewPersionInfo> hashSet=new HashSet<NewPersionInfo>();
//需要保留的字段
for (int i = 0; i < lists.size(); i++) {
String name = lists.get(i).getName();
String sex = lists.get(i).getSex();
//重写组合并赋值
NewPersionInfo newPersionInfo=new NewPersionInfo();
newPersionInfo.setName(name);
newPersionInfo.setSex(sex);
hashSet.add(newPersionInfo);
}
//添加到新的集合中
List<NewPersionInfo> list=new ArrayList<NewPersionInfo>();
list.clear();
list.addAll(hashSet);
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i).toString()+"===");
}
}
}
3.获取新的NewPersionInfo实体类
public class NewPersionInfo {
private String name;
private String sex;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
/**
* 根据对象的sex去重
*/
@Override
public boolean equals(Object object) {
NewPersionInfo info=(NewPersionInfo) object;
return sex.equals(info.sex);
}
/**
* 将字段名换成hashCode
*/
@Override
public int hashCode() {
//赋值比较
String names=sex;
return names.hashCode();
}
@Override
public String toString() {
return "NewPersionInfo [name=" + name + ", sex=" + sex + "]";
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/12887.html