java8的optional的使用:

http://www.jdon.com/idea/java/using-optional-effectively-in-java-8.html

http://www.runoob.com/java/java8-optional-class.html

Optional 类是一个可以为null的容器对象。如果值存在则isPresent()方法会返回true,调用get()方法会返回该对象。

Optional 是个容器:它可以保存类型T的值,或者仅仅保存null。Optional提供很多有用的方法,这样我们就不用显式进行空值检测。

Optional 类的引入很好的解决空指针异常。

在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 alpha = Arrays.asList("a", "b", "c", "d");

//Before Java8

List 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 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 num = Arrays.asList(1,2,3,4,5);

List 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;

//...

}

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 = 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 result = new ArrayList<>();

for (Staff x : staff) {

result.add(x.getName());

}

System.out.println(result); //[mkyong, jack, lawrence]

//Java 8

List collect = staff.stream().map(x -> x.getName()).collect(Collectors.toList());

System.out.println(collect); //[mkyong, jack, lawrence]

}

}

2.2如何在Java 8中将List转换为Map?

假设有一个员工对象

public class Employee {

// member variables

private int empId;

private String empName;

private int empAge;

private String empDesignation;

将这个员工对象放入LIst集合,如何转为Map? 首先要明确Map的key是什么?

1. 比如式样员工对象的empId作为key,值是员工姓名:

// convert List to Map using Java 8 Streams

Map mapOfEmployees = employees.stream().collect(Collectors.toMap(e -> e.getEmpId(),e -> e.getEmpName()));

2.Map的Key是empId,整个对象为Map的值:

// convert List to Map using Java 8 Streams

Map mapOfEmployees = employees.stream().collect(Collectors.toMap( e -> e.getEmpId(), e -> e));

3. 如果List中有重复的empId,映射到Map时,Key时不能重复的,如何解决?

默认情况时会抛重复异常,为了克服IllegalStateException重复键异常,我们可以简单地添加一个

BinaryOperator方法到toMap()中,这也称为合并功能,比如如果重复,可以取第一个元素:

Map mapOfEmployees = employees.stream().collect(

Collectors.toMap(

e -> e.getEmpId(),

e -> e.getEmpName(),

(e1, e2) -> e1 )); // Merge Function

4. 将List转换为Map - 使用TreeMap对键进行自然排序,或者指定的Map实现呢?

Map mapOfEmployees = employees.stream().collect(

Collectors.toMap(

e -> e.getEmpId(),

e -> e.getEmpName(),

(e1, e2) -> e1 , // Merge Function

TreeMap::new)); // Map Supplier

如果你的TreeMap实现需要加入比较器,将上面代码中TreeMap::new替换成:

() -> new TreeMap(new MyComparator())

3.1此示例说明如何将staff对象列表转换为对象列表StaffPublic。

Staff.java

package com.mkyong.java8;

import java.math.BigDecimal;

public class Staff {

private String name;

private int age;

private BigDecimal salary;

//...

}

StaffPublic.java

package com.mkyong.java8;

public class StaffPublic {

private String name;

private int age;

private String extra;

//...

}

3.2 Java 8之前。

BeforeJava8.java

package com.mkyong.java8;

import java.math.BigDecimal;

import java.util.ArrayList;

import java.util.Arrays;

import java.util.List;

public class BeforeJava8 {

public static void main(String[] args) {

List staff = Arrays.asList(

new Staff("mkyong", 30, new BigDecimal(10000)),

new Staff("jack", 27, new BigDecimal(20000)),

new Staff("lawrence", 33, new BigDecimal(30000))

);

List result = convertToStaffPublic(staff);

System.out.println(result);

}

private static List convertToStaffPublic(List staff) {

List result = new ArrayList<>();

for (Staff temp : staff) {

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!");

}

result.add(obj);

}

return result;

}

}

输出

[

StaffPublic{name='mkyong', age=30, extra='this field is for mkyong only!'},

StaffPublic{name='jack', age=27, extra='null'},

StaffPublic{name='lawrence', age=33, extra='null'}

]

3.3 Java 8的例子。

NowJava8.java

package com.mkyong.java8;

package com.hostingcompass.web.java8;

import java.math.BigDecimal;

import java.util.Arrays;

import java.util.List;

import java.util.stream.Collectors;

public class NowJava8 {

public static void main(String[] args) {

List 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 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);

}

}

输出

[

StaffPublic{name='mkyong', age=30, extra='this field is for mkyong only!'},

StaffPublic{name='jack', age=27, extra='null'},

StaffPublic{name='lawrence', age=33, extra='null'}

]

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐