java去掉List中的重复值代码

1. list中为字符串的情况,代码如下:

public static void main(String[] args) {
        List<String> li = new ArrayList<String>();
        li.add("AAAA");
        li.add("AAAA");
        li.add("AAAA");
        li.add("BBBB");
        li.add("BBBB");
        li.add("CCCC");
        li.add("CCCC");
        li.add("CCCC");
        li.add("CCCC");

        ArrayList<String> result = new ArrayList<String>();
        for (String s : li) {
            if (Collections.frequency(result, s) < 1)
                result.add(s);
        }
        for (int i = 0; i < result.size(); i++) {
            System.out.println(result.get(i));
        }
    }

输出结果为:
AAAA
BBBB
CCCC
2.如果list存放的是对象,可以借助Map来处理,因为Map中key值不能够重复的特点.

/***
     * 去除List<PartsInfoDTO>列表中的重复对象 ~!!
     * @param list
     * @return
     */
    public static List<PartsInfoDTO> removeDuplicate(List<PartsInfoDTO> list) {
//        Set<PartsInfoDTO> set = new HashSet<PartsInfoDTO>();
        List<PartsInfoDTO> newList = new ArrayList<PartsInfoDTO>();
        
        Map map = new HashMap();
        for (Iterator<PartsInfoDTO> iter = list.iterator(); iter.hasNext();) {
            PartsInfoDTO element = (PartsInfoDTO) iter.next();
            map.put(element.getId(), element); //如果id重复会覆盖.
        }
        
        Iterator it = map.keySet().iterator();   
        while (it.hasNext()) {   
           Integer key = (Integer) it.next();   
           newList.add((PartsInfoDTO) map.get(key));   
        }   

       return newList;
   }

另外补充下Map转换成List的方法:

/**
     * @param args
     */
    public static void main(String[] args) {

        Map map = new HashMap();
        map.put("a", "a1");
        map.put("b", "b1");
        map.put("c", "c1");

        List listKey = new ArrayList();
        List listValue = new ArrayList();
        Iterator it = map.keySet().iterator();
        while (it.hasNext()) {
            String key = it.next().toString();
            listKey.add(key);
            listValue.add(map.get(key));
        }
        System.out.println("Convert Finished !");

        for (int i = 0; i < listKey.size(); i++) {
            System.out.print("Key :" + listKey.get(i));
            System.out.println("     Value :" + listValue.get(i));
        }
    }
原文地址:https://www.cnblogs.com/simpledev/p/3491345.html