How do I remove repeated elements from ArrayList?

后端 未结 30 2461
难免孤独
难免孤独 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:40

    Java 8 streams provide a very simple way to remove duplicate elements from a list. Using the distinct method. If we have a list of cities and we want to remove duplicates from that list it can be done in a single line -

     List cityList = new ArrayList<>();
     cityList.add("Delhi");
     cityList.add("Mumbai");
     cityList.add("Bangalore");
     cityList.add("Chennai");
     cityList.add("Kolkata");
     cityList.add("Mumbai");
    
     cityList = cityList.stream().distinct().collect(Collectors.toList());
    

    How to remove duplicate elements from an arraylist

提交回复
热议问题