一.使用list集合去重
(String类型)如下显示:
String[] test = new String[]{"123", "113", "222", "333", "123", "123", "123"};
List<String> list1=new ArrayList<>();
for (int i = 0; i < test.length; i++) {
if (!list1.contains(test[i])) {
list1.add(test[i]);
}
}
System.out.println(JSON.toJSONString(list1));
输出如下:
["123","113","222","333"]
(int类型)如下显示:
int[] num={2,4,2,6,1,1,2,6,7};
List<Integer> list=new Arraylist<>();
for (int i: num){
if(!list.contains(i)){
list. add(i)
}
}
System. out. printin(list.toString();
输出如下:
[2,4,6,1,7]
二.使用Set集合去重
(包装类类型)如下显示:
Integer [] num1={ 2 , 4 , 5 , 6 ,3,2 , 5 , 6 , 7 };
Set <Integer> set=new Treeset < > ( Arrays.aslist ( num1) ) ;
for ( int i:num1){
set.add (i);
}
System . out . println ( set.toString ( ) );
输出如下:
[2,4,5,6,3,7]
(int类型)如下显示:
int[] num2={ 5 , 5 , 6 ,2 , 1,2,9,7 };
Set < Integer > set2=new Treeset < > ( ) ;
for ( int i:num2){
set2.add ( i ) ;
}
System . out . println ( set2.tostring ( ) ) ;
输出如下:
[5,6,2,1,9,7]
网友评论