-2

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 :-)

s2990
  • 13
  • 7
  • Here is your answer. https://stackoverflow.com/q/2644637/11567219 – Wolframm Dec 04 '19 at 19:50
  • Could be an [XY problem](https://meta.stackexchange.com/q/66377/351454): Why do you need to do that? If it is because you need to lookup strings without being case-sensitive, use a `new TreeSet<>(String.CASE_INSENSITIVE_ORDER)` instead of a `HashSet`, so you don't have to convert to lowercase when building the set *and* when looking up values. – Andreas Dec 04 '19 at 20:36

1 Answers1

2

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());
Andreas
  • 154,647
  • 11
  • 152
  • 247