Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to trim() String in List<String> using JAVA 8 Lambda expression [duplicate]

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 ].

like image 726
Sathish Kumar k k Avatar asked Apr 26 '16 18:04

Sathish Kumar k k


1 Answers

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());
like image 139
Eran Avatar answered Oct 24 '22 10:10

Eran