list去重三种方法

package com.kit.api.test.question;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

/**
 * @version: V1.0
 * @author: songyan
 * @className: ListDuplicateRemoval
 * @packageName: com.kit.api.test.question
 * @description: 列表去重
 * @date: 2021/3/24   8:55
 */
public class ListDuplicateRemoval {

    /**
     * @author: songyan
     * @methodsName: hashSetDuplicateRemoval
     * @param: list
     * @description: 基于HashSet元素不可重复去重
     * @return: void
     */
    public void hashSetDuplicateRemoval(List list) {
        HashSet hashSet = new HashSet(list);
        list.clear();
        list.addAll(hashSet);
    }

    /**
     * @author: songyan
     * @methodsName: containsDuplicateRemoval
     * @param: list
     * @description: 基于contains方法去重
     * @return: void
     */
    public List containsDuplicateRemoval(List list) {
        List list2 = new ArrayList();
        if (list != null) {
            for (Object obj : list) {
                if (!list2.contains(obj)) {
                    list2.add(obj);
                }
            }
        }
        return list2;
    }

    /**
     * @author: songyan
     * @methodsName: forDuplicateRemoval
     * @description: for循环去重
     * @return: java.util.List
     */
    public void forDuplicateRemoval(List list) {
        for (int i = 0; i < list.size(); i++) {
            for (int j = list.size() - 1; j > i; j--) {
                if (list.get(i).equals(list.get(j))) {
                    list.remove(j);
                }
            }
        }
    }

}
原文地址:https://www.cnblogs.com/excellencesy/p/14572076.html