Search code examples
javastringcollectionshashsetlowercase

How to convert all String's to lower case in a collection of type HashSet <String>?


I am not sure of best way to convert all Strings in a collection to lowercase. Any thoughts?

    private Set<String> email;    

    if(userEmail instanceof Collection) {
    this.email = new HashSet<String>((Collection<String>) userEmail);
    model.put("userEmail", this.email); //need to convert this to lower case
}

Thanks in advance :-)


Solution

  • To convert values in the Set to lowercase, don't use that constructor, just convert the strings to lowercase before adding them to the set:

    this.email = ((Collection<String>) userEmail).stream()
            .map(String::toLowerCase).collect(Collectors.toSet());
    

    or

    this.email = new HashSet<>();
    for (String s : (Collection<String>) userEmail)
        this.email.add(s.toLowerCase());