Using stream api to set strings all lowercase but capitalize first letter

  • A+
Category:Languages

I have strings in a list and through only using the stream api I was settings all strings to lowercase, sorting them from smallest string to largest and printing them. The issue I'm having is capitalizing the first letter of the string. Is that something I do through .stream().map()?

Main:

public static void main(String[] args) {      List<String> list = Arrays.asList("SOmE", "StriNgs", "fRom", "mE", "To", "yOU");     list.stream().map(n -> n.toLowerCase())         .sorted((a, b) -> a.length() - b.length())         .forEach(n -> System.out.println(n));;  } 

Output:

me to you some from strings 

Desired output:

Me To You Some From Strings 

 


Something like this should suffice:

 list.stream()      .map(n -> n.toLowerCase())      .sorted(Comparator.comparingInt(String::length))      .map(s -> Character.toUpperCase(s.charAt(0)) + s.substring(1))      .forEach(n -> System.out.println(n)); 
  1. note that I've changed the comparator, which is essentially the idiomatic approach to do it.
  2. I've added a map operation after sorting to uppercase the first letter.

Comment

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