The Java 8,stream (). Map () allows you to convert objects to something else. Review the following example:
1. String-type list set capitalization
1.1 Simple Java Example converts a list of strings to uppercase. Testjava8.java
Package com.mkyong.java8;
Import java.util.ArrayList;
Import Java.util.Arrays;
Import java.util.List;
Import java.util.stream.Collectors; public class TestJava8 {public static void main (string[] args) {list<string> alpha = arrays.aslist ("
A "," B "," C "," D ");
Before Java8 list<string> alphaupper = new arraylist<> ();
for (String S:alpha) {Alphaupper.add (S.touppercase ()); } System.out.println (Alpha); [A, B, C, d] System.out.println (Alphaupper); [A, B, C, D]//Java 8 list<string> collect = Alpha.stream (). Map (String::touppercase). Collect (Col
Lectors.tolist ()); SYSTEM.OUT.PRINTLN (collect);
[A, B, C, D]//Extra, streams apply to any data type.
list<integer> num = arrays.aslist (1,2,3,4,5);
list<integer> Collect1 = Num.stream (). Map (n-> n * 2). Collect (Collectors.tolist ()); System.out.println (COLLECT1); [2, 4, 6, 8, 10]}}
2. List of objects-> List of String
2.1 Gets all the name values from the Staff object collection. Staff.java
Package com.mkyong.java8;
Import Java.math.BigDecimal;
public class Staff {
private String name;
private int age;
Private BigDecimal salary;
//...
}
Testjava8.java
Package com.mkyong.java8;
Import Java.math.BigDecimal;
Import java.util.ArrayList;
Import Java.util.Arrays;
Import java.util.List;
Import java.util.stream.Collectors;
public class TestJava8 {public static void main (string[] args) {list<staff> Staff = arrays.aslist ( New Staff ("Mkyong", New BigDecimal (10000)), New Staff ("Jack", New BigDecimal (20000)
), New Staff ("Lawrence", New BigDecimal (30000));
Before Java 8 list<string> result = new arraylist<> ();
for (Staff x:staff) {Result.add (X.getname ()); } System.out.println (Result); [Mkyong, Jack, Lawrence]//java 8 list<string> collect = Staff.stream (). Map (x-> x.getname ()).
Collect (Collectors.tolist ()); SYSTEM.OUT.PRINTLN (collect); [Mkyong, Jack, Lawrence]}}
3. List of objects-> List of other objects
3.1 This example shows how to convert a collection of staff objects to a collection of Staffpublic objects. Staff.java
Package Com.mkyong.java8