Java中判断List集合中是否有重复元素的方法

时间:2025-03-21 09:38:27

package ;

import ;
import ;
import ;

public class TestList {
	public static void main(String[] args) {

		List<String> list = new ArrayList<>();

		("张三");
		for (int i = 0; i < 100000; i++) {
			(i+"test");
		}
		("张三");

		long start1 = ();
		("test1----" + test1(list));
		long end1 = ();
		("test耗时:" + (end1 - start1) + "ms");

		long start2 = ();
		("test2----" + test2(list));
		long end2 = ();
		("test耗时:" + (end2 - start2) + "ms");
	}

	private static Boolean test1(List list) {

		HashSet<String> set = new HashSet<>(list);

		Boolean result = () == () ? true : false;

		return result;
	}

	// 伴随for循环多次contains(内部也是循环),数据量大性能会明显降低
	private static Boolean test2(List<String> list) {

		List<String> list2 = new ArrayList<>();

		for (String one : list) {

			if ((one)) {
				return false;
			}
			(one);
		}
		return true;
	}
}

运行结果:
test1----false
test耗时:17ms
test2----false
test耗时:34614ms



续更。。。
  public static List test3(List<Integer> list) {
      List newList = ().distinct().collect(());
      return newList;
  }

  public static List test4(List<Integer> list) {
      TreeSet set = new TreeSet(list);
      //把List集合所有元素清空
      ();
      //把HashSet对象添加至List集合,转回list
      (set);
      return list;
  }

  public static List test5(List<Integer> list) {
      LinkedHashSet<Integer> linkedHashSet = new LinkedHashSet<>(list);
      //把List集合所有元素清空
      ();
      //把linkedHashSet对象添加至List集合,转回会list
      (linkedHashSet);
      return list;
  }