Sample Java remove duplicate elements from collection share Java remove duplicate

  • 2020-04-01 02:43:33
  • OfStack


class ArrayListTest1 {
    public static void main(String[] args) {
        ArrayList al = new ArrayList();
        al.add("java03");
        al.add("java03");
        al.add("java01");
        al.add("java02");
        al.add("java01");
        al.add("java02");
        al.add("java01");
        System.out.println(al);

        al = singleElement(al);
        System.out.println(al);

    }
    //Returning the List is appropriate
    public static ArrayList singleElement(ArrayList al){
      //Define a temporary container
      ArrayList newAl = new ArrayList();
      //Next is called once in the iteration loop, and hasNext is judged once
      Iterator it = al.iterator();

       while (it.hasNext()){
         Object obj = it.next();//It is best to call next() once and judge hasNext() once or it is prone to exceptions
         if (!newAl.contains(obj))
            newAl.add(obj);
        }
        return newAl;
    }
}


Related articles: