Java 8 remove duplicate strings irrespective of case from a list

  • A+
Category:Languages

How can we remove duplicate elements from a list of String without considering the case for each word, for example consider below code snippet

    String str = "Kobe Is is The the best player In in Basketball basketball game .";     List<String> list = Arrays.asList(str.split("//s"));     list.stream().distinct().forEach(s -> System.out.print(s+" ")); 

This still gives the same output as below, which is obvious

Kobe Is is The the best player In in Basketball basketball game . 

I need the result as follows

Kobe Is The best player In Basketball game . 

 


Taking your question literally, to “remove duplicate strings irrespective of case from a list”, you may use

// just for constructing a sample list String str = "Kobe Is is The the best player In in Basketball basketball game ."; List<String> list = new ArrayList<>(Arrays.asList(str.split("//s")));  // the actual operation TreeSet<String> seen = new TreeSet<>(String.CASE_INSENSITIVE_ORDER); list.removeIf(s -> !seen.add(s));  // just for debugging System.out.println(String.join(" ", list)); 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: