list排序加去重功能

来源:互联网 发布:黑马校对软件下载 编辑:程序博客网 时间:2024/04/30 00:03

最近遇到一个问题,需要在list的去重功能,在网上找了很多,都没有好的解决办法,发现好多人在用重载hashCode和equals来实现去重,于是就尝试了下,最后还真可以,你需要在你的实体类中重载hashCode和equals代码如下:

package com.cs.flyox.flyox.entity;import java.io.Serializable;import java.util.List;public class Event implements Serializable{    private static final long serialVersionUID = 1L;    private int eventid;    private String localid;    public int getEventid() {        return eventid;    }    public void setEventid(int eventid) {        this.eventid = eventid;    }    public String getLocalid() {        return localid;    }    public void setLocalid(String localid) {        this.localid = localid;    }        @Override    public int hashCode() {        String aaString = localid + eventid;        return aaString.hashCode();    }            @Override    public boolean equals(Object o) {                if(o == this)            return true;        if(o == null)            return false;        Event event = (Event)o;        if(event.getLocalid().equals(this.getLocalid()))            return true;                return true;    }}
使用时,需要配合HashSet使用,将你的list的数据先加到hashset的中,在将list的清除,然后在将去重的hashset数据加回到list中,这样就可以实现去重了。

 HashSet<Event> h = new HashSet<Event>(list);         list.clear();           list.addAll(h); 
用过hashset 的程序猿们都知道,hsahset的是没有顺序的,如果想要排序一下的方法可以满足你,代码如下:

 public class SortList<E>{          public void Sort(List<E> list, final String method, final String sort){            Collections.sort(list, new Comparator<Object>() {                           @SuppressWarnings("unchecked")                public int compare(Object a, Object b) {                    int ret = 0;                    try{                        Method m1 = ((E)a).getClass().getMethod(method, null);                        @SuppressWarnings("unchecked")                        Method m2 = ((E)b).getClass().getMethod(method, null);                        if(sort != null && "desc".equals(sort))//倒序                            ret = m2.invoke(((E)b), null).toString().compareTo(m1.invoke(((E)a), null).toString());                         else//正序                            ret = m1.invoke(((E)a), null).toString().compareTo(m2.invoke(((E)b), null).toString());                    }catch(NoSuchMethodException ne){                        System.out.println(ne);                    }catch(IllegalAccessException ie){                        System.out.println(ie);                    }catch(InvocationTargetException it){                        System.out.println(it);                    }                    return ret;                }             });        }    }
用法:

SortList<Event> sortList = new SortList<Event>();           sortList.Sort(list, "getEventid", "desc");





0 0