在开发过程中,碰到生成一个List对象,需要对其里面的每个对象都进行校验。但是,这个List有时候存在重复的数据。因此需要进行去重,以避免重复的校验。
1.不带类型写法:
1
|
List listWithoutDup = new ArrayList( new HashSet(listWithDup));
|
2.带类型写法(以String类型为例):
1)Java 7以下写法:
1
|
List<string> listWithoutDup = new ArrayList<string>( new HashSet<string>(listWithDup));
|
2)Java 7及以上写法:
1
|
List<string> listWithoutDup = new ArrayList<>( new HashSet<>(listWithDup));
|
样例:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
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]