How to crop () a String in a <String> using a JAVA 8 Lambda expression

I am looking for all types of manipulations using java 8 Lambda expressions.

First I tried the method trim()in a simple Stringlist.

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());

In this example, I expected to receive [S1, S2 EE, EE S1], but I received [ S1, S2 EE , EE S1 ].

+4
source share
1 answer

collect()creates a new one List, so you must assign this to Listyour variable so that it contains the trimmed one String:

ls = ls.stream().map(String :: trim).collect(Collectors.toList());
+12
source

All Articles