Removing Duplicate Values from ArrayList

后端 未结 18 1166
无人及你
无人及你 2020-11-30 03:24

I have one Arraylist of String and I have added Some Duplicate Value in that. and i just wanna remove that Duplicate value So how to remove it.

Here Example I got o

相关标签:
18条回答
  • 2020-11-30 03:45

    list = list.stream().distinct().collect(Collectors.toList());
    This could be one of the solutions using Java8 Stream API. Hope this helps.

    0 讨论(0)
  • 2020-11-30 03:47

    This will be the best way

        List<String> list = new ArrayList<String>();
        list.add("Krishna");
        list.add("Krishna");
        list.add("Kishan");
        list.add("Krishn");
        list.add("Aryan");
        list.add("Harm");
    
        Set<String> set=new HashSet<>(list);
    
    0 讨论(0)
  • 2020-11-30 03:47

    Using java 8:

    public static <T> List<T> removeDuplicates(List<T> list) {
        return list.stream().collect(Collectors.toSet()).stream().collect(Collectors.toList());
    }
    
    0 讨论(0)
  • 2020-11-30 03:48

    if you want to use only arraylist then I am worried there is no better way which will create a huge performance benefit. But by only using arraylist i would check before adding into the list like following

    void addToList(String s){
      if(!yourList.contains(s))
           yourList.add(s);
    }
    

    In this cases using a Set is suitable.

    0 讨论(0)
  • 2020-11-30 03:48

    In case you just need to remove the duplicates using only ArrayList, no other Collection classes, then:-

    //list is the original arraylist containing the duplicates as well
    List<String> uniqueList = new ArrayList<String>();
        for(int i=0;i<list.size();i++) {
            if(!uniqueList.contains(list.get(i)))
                uniqueList.add(list.get(i));
        }
    

    Hope this helps!

    0 讨论(0)
  • 2020-11-30 03:53

    You can make use of Google Guava utilities, as shown below

     list = ImmutableSet.copyOf(list).asList(); 
    

    This is probably the most efficient way of eliminating the duplicates from the list and interestingly, it preserves the iteration order as well.

    UPDATE

    But, in case, you don't want to involve Guava then duplicates can be removed as shown below.

    ArrayList<String> list = new ArrayList<String>();
        list.add("Krishna");
        list.add("Krishna");
        list.add("Kishan");
        list.add("Krishn");
        list.add("Aryan");
        list.add("Harm");
    
    System.out.println("List"+list);
    HashSet hs = new HashSet();
    hs.addAll(list);
    list.clear();
    list.addAll(hs);
    

    But, of course, this will destroys the iteration order of the elements in the ArrayList.

    Shishir

    0 讨论(0)
提交回复
热议问题