Search This Blog

Breaking

Wednesday, 5 August 2020

Find duplicate values from a string with Java8 features

This is another very common question. It can be done in one line through Java8.



String myString = "This is for test automation questions";
String distinctChar =  myString
                       .chars()
                       .mapToObj(c -> (char) c)
                       .collect(Collectors.toSet())
                       .stream()
                       .map(String::valueOf)
                        .collect(Collectors.joining());

System.out.println("String after duplicates removed: "
        +  String.valueOf(disticntChar));

No comments:

Post a Comment