1. 程式人生 > >JAVA8中的Lamdba表示式之Map

JAVA8中的Lamdba表示式之Map

在Java 8中stream().map(),可以將物件轉換為其他物件。檢視以下示例:

1.大寫字串列表

1.1簡單的Java示例將Strings列表轉換為大寫。

 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物件列表中獲取所有值

 List<Staff> staff = Arrays.asList(
                new Staff("mkyong", 30, new BigDecimal(10000)),
                new Staff("jack", 27, new BigDecimal(20000)),
                new Staff("lawrence", 33, 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.物件列表 - >其他物件列表

3.1此示例說明如何將staff物件列表轉換為物件列表StaffPublic。

public class Staff {
 
    private String name;
    private int age;
    private BigDecimal salary;
    //...
}

public class StaffPublic {
 
    private String name;
    private int age;
    private String extra;
    //...
}

        List<Staff> staff = Arrays.asList(
                new Staff("mkyong", 30, new BigDecimal(10000)),
                new Staff("jack", 27, new BigDecimal(20000)),
                new Staff("lawrence", 33, new BigDecimal(30000))
        );
 
        // convert inside the map() method directly.
        List<StaffPublic> result = staff.stream().map(temp -> {
            StaffPublic obj = new StaffPublic();
            obj.setName(temp.getName());
            obj.setAge(temp.getAge());
            if ("mkyong".equals(temp.getName())) {
                obj.setExtra("this field is for mkyong only!");
            }
            return obj;
        }).collect(Collectors.toList());
 
        System.out.println(result);

轉載於:https://www.cnblogs.com/fengli9998/p/9002377.html