1.不带类型写法:
List listWithoutDup = new ArrayList(new HashSet(listWithDup));
2.带类型写法(以String类型为例):
1)Java 7以下写法:
List<String> listWithoutDup = new ArrayList<String>(new HashSet<String>(listWithDup));
2)Java 7及以上写法:
List<String> listWithoutDup = new ArrayList<>(new HashSet<>(listWithDup));
样例:
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
public class Test {
public static void main(String[] args) {
List<String> listWithDup = new ArrayList<String>();
listWithDup.add("1");
listWithDup.add("2");
listWithDup.add("3");
listWithDup.add("1");
List<String> listWithoutDup = new ArrayList<String>(new HashSet<String>(listWithDup));
System.out.println("list with dup:"+ listWithDup);
System.out.println("list without dup:"+ listWithoutDup);
}
}
样例运行结果:
list with dup:[1, 2, 3, 1]
list without dup:[3, 2, 1]
list without dup:[3, 2, 1]