0

I'm trying to capitalize the first letter of each word in a List. Currently, I'm getting a "Lambda Expression not expected here", and I'm told that I can't convert a String to a void, which I'm not trying to do. I'm trying to capitalize the first letter of each string in an arrayList; I haven't been able to determine a way to do so without selecting+capitalizing the first char (as char or as substring) and then adding the rest of the word.

public List<String> capitalizeAllWords(ArrayList<String> words) {
   return words.stream().collect(Collectors.toList().forEach(word ->
     word.substring(0,1).toUpperCase() + word.substring(1))
   );
  }
  • 2
    Your transformations must be made before collecting. `Collectors.toList()` gives you a Collector, you can't call `forEach` on it. (`word -> word.substring(0,1).toUpperCase() + word.substring(1))` is given to `map`). You don't need to call `forEach` at all – ernest_k Jul 28 '20 at 04:37
  • 3
    (The previous duplink was incorrect. Capitalizing words in a string is a different problem to capitalizing strings in a list of strings.) – Stephen C Jul 28 '20 at 05:19

1 Answers1

3

Use .map before collecting.

public List<String> capitalizeAllWords(ArrayList<String> words) {
   return words.stream()
       .map(word -> Character.toUpperCase(word.charAt(0)) + word.substring(1))
       .collect(Collectors.toList());
}
MC Emperor
  • 22,334
  • 15
  • 80
  • 130
Unmitigated
  • 76,500
  • 11
  • 62
  • 80