loop each element and perform its own action and then store it in list<String>

Anonymous :

I want to loop each element in the list. Within each element we still have actions for it, I wanted to implement these actions and then store it in a list form.

List<String> Str = words.stream().forEach(x->x.getSentenceStr().toLowerCase()).collect(Collectors.toList());

I received an error when trying to use my method:

cannot invoke collect on primitive type void.

I thought the forEach is use to loop each element in the list and if I perform certain action within each element, it will then return back the output while still looping it? Lastly, the collect will then collect all these output and convert it to list of string. Am I having the wrong understanding of this forEach function?

Here is my dummy trial:

    List<String> s = new ArrayList<String>(Arrays.asList("a","b", "c"));
    List<String> ss = s.stream().forEach(x->x.toLowerCase()).collect(Collectors.toList());
    System.out.print(s);
Elliott Frisch :

forEach is void, you need a map like

List<String> ss = s.stream().map(x -> x.toLowerCase()).collect(Collectors.toList());

and you could use the shorter functional invocation of String.toLowerCase() like

List<String> ss = s.stream().map(String::toLowerCase).collect(Collectors.toList());

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=130062&siteId=1