package com.fdd;
import java.util.*;
/**
* @uthor lihongliang on 2017/9/22 17:36
* @Emile li_fdd@163.com
* @Description : 去除List集合中的重复值
*/
public class ListTest {
//set集合去重,不打乱顺序
public static void repeatList(){
List<String> list = new ArrayList<String>();
list.add("111");
list.add("222");
list.add("333");
list.add("111");
Set set = new HashSet();
List newList = new ArrayList();
for (String cd:list) {
if(set.add(cd)){
newList.add(cd);
}
}
System.out.println( "去重后的集合: " + newList);
}
public static void repeatList2(){
List<String> list = new ArrayList<String>();
list.add("111");
list.add("222");
list.add("333");
list.add("111");
List<String> newList = new ArrayList<String>();
for (String cd:list) {
if(!newList.contains(cd)){
newList.add(cd);
}
}
System.out.println( "去重后的集合: " + newList);
}
public static void repeatList3(){
List<String> list = new ArrayList<String>();
list.add("111");
list.add("222");
list.add("333");
list.add("111");
Set set = new HashSet();
List newList = new ArrayList();
set.addAll(list);
newList.addAll(set);
System.out.println( "去重后的集合: " + newList);
}
public static void repeatList4(){
List<String> list = new ArrayList<String>();
list.add("111");
list.add("222");
list.add("333");
list.add("111");
List newList = new ArrayList(new HashSet(list));
System.out.println( "去重后的集合: " + newList);
}
/**
* hashset不进行排序,还有一种方法是用treeset,去重并且按照自然顺序排列,将hashset改为treeset就可以了。
* (原本的顺序是改变的,只是按照字母表顺序排列而已)
*/
public static void repeatList5(){
List<String> list = new ArrayList<String>();
list.add("111");
list.add("222");
list.add("333");
list.add("111");
List newList = new ArrayList(new TreeSet(list));
System.out.println( "去重后的集合: " + newList);
}
public static void main(String[] args){
ListTest.repeatList();
ListTest.repeatList2();
ListTest.repeatList3();
ListTest.repeatList4();
ListTest.repeatList5();
}
}