1. Remove duplicate elements in List
method 1:
public static void removeDuplicate(List list) {
for (int i = 0; i < list.size() - 1; i++) {
for (int j = list.size() - 1; j > i; j--) {
if (list.get(j).equals(list.get(i))) {
list.remove(j);
}
}
}
System.out.println(list);
}
Method 2:
Delete duplicate elements in ArrayList, add order may change, you can use it regardless of order
public static void removeDuplicate1(List list) {
HashSet h = new HashSet(list);
list.clear();
list.addAll(h);
System.out.println(list);
}
Method 3:
public static void getNewList(List<String> li){
List<String> list = new ArrayList<String>();//创建新的list
for(int i=0; i<li.size(); i++){
//获取传入集合对象的每一个元素
String str = li.get(i);
//查看新集合中是否有指定的元素,如果没有则加入
if(!list.contains(str)){
list.add(str);
}
}
System.out.println(list); //返回集合
}
2. Determine whether the list is duplicate
1. Determine whether all elements are repeated, all repeated as true, otherwise return false
private static boolean hasSame(List<? extends Object> list) {
if(null == list)
return false;
return 1 == new HashSet<Object>(list).size();
}
2. Are there duplicate elements
private static boolean hasSame(List<? extends Object> list)
{
if(null == list)
return false;
return list.size() == new HashSet<Object>(list).size();
}
3. Randomly take 10 numbers from the list
//Get 10 pieces of data randomly
public List<Integer> getRandom(List<Integer> oldList){
List<Integer> newList = new ArrayList<>();
for(int i=0;i<10;i++) {
Random random = new Random();
int index = random.nextInt(oldList.size());
newList.add(oldList.get(index));
oldList.remove(index);
}
return newList;
}