stream.map示例
引用1:https://blog.csdn.net/sanchan/article/details/70753645
引用2:https://www.ibm.com/developerworks/cn/java/j-lo-java8streamapi/
在Java 8中stream().map()
,您可以将对象转换为其他对象。查看以下示例:
1.大写字符串列表
1.1简单的Java示例将Strings列表转换为大写。
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(Collectors.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.对象列表 – >字符串列表
2.1 name
从staff
对象列表中获取所有值。
Staff.java
package com.mkyong.java8;
import java.math.BigDecimal;
public class Staff {
private String name;
private int age;
private BigDecimal salary;
//...
}