您的位置:首页 > 其它

List<T>中去除重复的元素

2016-09-09 09:33 507 查看
pojo类

package com.easzz.model.entity;

import java.util.List;

public class JsonData {
private Integer id; //省级id

private Integer pid; //父id

private String text; //名称
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((children == null) ? 0 : children.hashCode());
result = prime * result + ((disable == null) ? 0 : disable.hashCode());
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((pid == null) ? 0 : pid.hashCode());
result = prime * result + ((text == null) ? 0 : text.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;
JsonData other = (JsonData) obj;
if (children == null) {
if (other.children != null)
return false;
} else if (!children.equals(other.children))
return false;
if (disable == null) {
if (other.disable != null)
return false;
} else if (!disable.equals(other.disable))
return false;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (pid == null) {
if (other.pid != null)
return false;
} else if (!pid.equals(other.pid))
return false;
if (text == null) {
if (other.text != null)
return false;
} else if (!text.equals(other.text))
return false;
return true;
}

private Integer disable;
private List<JsonData> children;

public Integer getDisable() {
return disable;
}

public void setDisable(Integer disable) {
this.disable = disable;
}

public List<JsonData> getChildren() {
return children;
}

public void setChildren(List<JsonData> children) {
this.children = children;
}

public Integer getId() {
return id;
}

public void setId(Integer id) {
this.id = id;
}

public Integer getPid() {
return pid;
}

public void setPid(Integer pid) {
this.pid = pid;
}

public String getText() {
return text;
}

public void setText(String text) {
this.text = text == null ? null : text.trim();
}
}


工具类

public static List<JsonData> removeDuplicate(List<JsonData> list) {
HashSet<JsonData> h = new HashSet<JsonData>(list);
list.clear();
list.addAll(h);
return list;
}


操作类

//获取父级数据
List<JsonData> pDatas=new ArrayList<JsonData>();
for (JsonData jsonData : findByRemovedPid) {
JsonData pdata = jsonDataService.findByPid(jsonData.getPid());
pDatas.add(pdata);
}
List<JsonData> removeDuplicate = removeDuplicate(pDatas);
for(int i=0;i<removeDuplicate.size();i++){
System.out.println(removeDuplicate.get(i).getText());
}


如果是对象,需要实现hashCode()和equals()方法。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: