HashMap去重

package util;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
/**
 *
 * HashMap去重处理
 *
 * @author 16060834
 * @see [相关类/方法](可选)
 * @since [产品/模块版本] (可选)
 */
public class DuplicateMapData {
    public static void main(String[] args) {
        Map<String, String> map = new HashMap<String, String>();
        map.put("1", "123");
        map.put("2", "djw");
        map.put("3", "djw");
        map.put("4", "123");
        map.put("5", "djw");
        System.out.println(deleteDuplicate1(map));
        deleteDuplicate2(map);
        System.out.println(map);
    }
    
    /**
     *
     * 方法1:通过containsValue去重后放入新定义map
     *
     * @param map
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    private static Map<String, String> deleteDuplicate1(Map<String, String> map) {
        if (map == null || map.size() == 0) {
            return new HashMap<String, String>();
        }
        Map<String, String> map2 = new HashMap<String, String>();
        for (Iterator<Entry<String, String>> iterator = map.entrySet().iterator(); iterator.hasNext();) {
            Entry<String, String> entry = iterator.next();
            if (map2.containsValue(entry.getValue())) {
                continue;
            } else {
                map2.put(entry.getKey(), entry.getValue());
            }
        }
        return map2;
    }
    
    /**
     *
     * 利用set不可重复特性进行判断
     *
     * @param map
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    private static void deleteDuplicate2(Map<String, String> map) {
        if (map == null || map.size() == 0) {
            return;
        }
        Set<String> set = new HashSet<String>();
        for (Iterator<Entry<String, String>> iterator = map.entrySet().iterator(); iterator.hasNext();) {
            Entry<String, String> entry = iterator.next();
            if (set.contains(entry.getValue())) {
                iterator.remove();
                continue;
            } else {
                set.add(entry.getValue());
            }
        }
    }

}

posted @ 2018-04-22 16:23  前度刘郎  阅读(13138)  评论(0编辑  收藏  举报
欢迎来到戴建伟的博客!