Java8's stream().map() usage
This scenario may be encountered during Java encoding
Iterate through a list and convert, assign and other operations on the properties in the list to form a new list we want. Usually our conventional idea is to use the for loop directly.
After Java 8 introduces lambda expressions, we can use stream stream chain processing to form new streams to achieve the expected effect.
There are many stream operations, and here we mainly focus on map()
List the following three columns
Experience the usage of stream().map().collect(()) for collection element processing.
package .java8; import ; import ; import ; public class StreamMap { private static class People{ private String name; private Integer age; private String address; // Only the constructor is given, ignoring the get/set details public People(String name, Integer age, String address) { = name; = age; = address; } } public static class PeoplePub{ private String name; private Integer age; // Only the constructor is given, ignoring the get/set details public PeoplePub(String name, Integer age) { = name; = age; } // Rewrite the toString method public String toString(){ return "(" + + "," + + ")"; } } public static void main(String[] args) { List<People> peoples = ( new People("zs", 25, "cs"), new People("ls", 28, "bj"), new People("ww", 23, "nj") ); // List -> String List<String> names = ().map(p -> ()).collect(()); // Stream stream implements English letters to capitalize List<String> upNames = ().map(String::toUpperCase).collect(()); // stream stream implements numeric multiplication List<Integer> ages = ().map(p -> () * 2).collect(()); // list - > new List List<PeoplePub> peoplePubs = ().map(p -> { return new PeoplePub((), ()); }).collect(()); ("to print upnames List : " + upNames); ("to print ages List : " + ages); ("to print new people List" + ()); } }
Console printing results:
to print upnames List : [ZS, LS, WW]
to print ages List : [50, 56, 46]
to print new people List[(zs,25), (ls,28), (ww,23)]
Summarize
The above is personal experience. I hope you can give you a reference and I hope you can support me more.