How do I remove repeated elements from ArrayList?

后端 未结 30 1737
难免孤独
难免孤独 2020-11-21 06:24

I have an ArrayList, and I want to remove repeated strings from it. How can I do this?

30条回答
  •  醉梦人生
    2020-11-21 06:44

    LinkedHashSet will do the trick.

    String[] arr2 = {"5","1","2","3","3","4","1","2"};
    Set set = new LinkedHashSet(Arrays.asList(arr2));
    for(String s1 : set)
        System.out.println(s1);
    
    System.out.println( "------------------------" );
    String[] arr3 = set.toArray(new String[0]);
    for(int i = 0; i < arr3.length; i++)
         System.out.println(arr3[i].toString());
    

    //output: 5,1,2,3,4

提交回复
热议问题