将列表数组中的首字母大写,而不产生空值。

huangapple go评论76阅读模式
英文:

capitalizing first letters in listArray without producing void

问题

public List<String> capitalizeAllWords(ArrayList<String> words) {
   return words.stream().map(word ->
     word.substring(0, 1).toUpperCase() + word.substring(1))
     .collect(Collectors.toList());
}
英文:

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&lt;String&gt; capitalizeAllWords(ArrayList&lt;String&gt; words) {
   return words.stream().collect(Collectors.toList().forEach(word -&gt;
     word.substring(0,1).toUpperCase() + word.substring(1))
   );
  }

答案1

得分: 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());
}
英文:

Use .map before collecting.

public List&lt;String&gt; capitalizeAllWords(ArrayList&lt;String&gt; words) {
   return words.stream()
       .map(word -&gt; Character.toUpperCase(word.charAt(0)) + word.substring(1))
       .collect(Collectors.toList());
}

huangapple
  • 本文由 发表于 2020年7月28日 12:33:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/63127073.html
匿名

发表评论

匿名网友

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

确定