10

I am looking for all type of string manipulation using java 8 Lambda expressions.

I first tried the trim() method in simple String list.

String s[] = {" S1","S2 EE ","EE S1 "};
List<String> ls = (List<String>) Arrays.asList(s);
ls.stream().map(String :: trim).collect(Collectors.toList());
System.out.println(ls.toString());

For this example, I was expecting to get [S1, S2 EE, EE S1], but I got [ S1, S2 EE , EE S1 ].

Eran
  • 387,369
  • 54
  • 702
  • 768
Sathish Kumar k k
  • 1,732
  • 5
  • 26
  • 45

1 Answers1

31

collect() produces a new List, so you must assign that List to your variable in order for it to contain the trimmed Strings :

ls = ls.stream().map(String :: trim).collect(Collectors.toList());
Eran
  • 387,369
  • 54
  • 702
  • 768
  • 19
    Or just do the whole op in-place: `ls.replaceAll(String::trim);` – Holger Apr 26 '16 at 18:45
  • So now I have 2 solutions and both are working perfect. Now which one of these do I need to use as a best practice. – Sathish Kumar k k Apr 26 '16 at 19:03
  • @SathishKumarkk Well, Holger's suggestion is more elegant and saves the creation of a new List instance, so I'd use it. – Eran Apr 26 '16 at 19:06
  • @Eran Thanks! And where can I refer for all string manipulation on a list using lambda. – Sathish Kumar k k Apr 26 '16 at 19:14
  • @SathishKumarkk I don't understand your question. If you have a specific question you can't find the answer to, you can always post a new question here. – Eran Apr 26 '16 at 19:17
  • @SathishKumarkk I would suggest you to read the Oracle Stream tutorial https://docs.oracle.com/javase/tutorial/collections/streams/. They are quite comprehensive and cover a lot of aspects. – Tunaki Apr 26 '16 at 19:21