1. 程式人生 > >List中去除重複的元素

List中去除重複的元素

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()方法。