Java 8 新特性使用
Optional类
-
Optional 类是一个可以为null的容器对象。如果值存在则isPresent()方法会返回true,调用get()方法会返回该对象。
-
Optional 是个容器:它可以保存类型T的值,或者仅仅保存null。Optional提供很多有用的方法,这样我们就不用显式进行空值检测。
-
Optional 类的引入很好的解决空指针异常。
Optional类源码
public final class Optional<T> {
// 这个是通用的代表NULL值的Optional实例
private static final Optional<?> EMPTY = new Optional<>();
// 泛型类型的对象实例
private final T value;
// 实例化Optional,注意是私有修饰符,value置为NULL
private Optional() {
this.value = null;
}
// 直接返回内部的EMPTY实例
public static<T> Optional<T> empty() {
@SuppressWarnings("unchecked")
Optional<T> t = (Optional<T>) EMPTY;
return t;
}
// 通过value实例化Optional,如果value为NULL则抛出NPE
private Optional(T value) {
this.value = Objects.requireNonNull(value);
}
// 通过value实例化Optional,如果value为NULL则抛出NPE,实际上就是使用Optional(T value)
public static <T> Optional<T> of(T value) {
return new Optional<>(value);
}
// 如果value为NULL则返回EMPTY实例,否则调用Optional#of(value)
public static <T> Optional<T> ofNullable(T value) {
return value == null ? empty() : of(value);
}
}
创建一个空的Optional
Optional<User> emptyOpt = Optional.empty();
emptyOpt.get();
创建有值的Optional
Optional<User> emptyOpt = Optional.of(user);
User user1 = emptyOpt.get();
logger.info(JSONObject.toJSONString(user1));
空值判断
// name不为空 否则orelse
String testname = Optional.ofNullable(user.getName()).orElse("李四");
logger.info(testname);
orElseGet 赋值对象
User user1 = new User(1, "张三", "西安");
User user2 = new User(2, "李四", "新疆");
user1 = null;
User user = Optional.ofNullable(user1).orElseGet(() -> user2);
logger.info(user.toString());
orElseThrow 抛出空指针
User user = new User(1, "张三", "西安");
user =null;
User result = Optional.ofNullable(user).orElseThrow(() -> new IllegalArgumentException());
map链式操作
User user = new User(1, "zhangSan_LISI", "西安");
String names = Optional.of(user)
.map(u -> u.getName())
.map(name -> name.toLowerCase())
.map(str -> str.replace("_", ""))
.orElseThrow(() -> new NullPointerException("空指针异常"));
logger.info(names);
Stream流
在 Java 8 中, 集合接口有两个方法来生成流:
- stream() − 为集合创建串行流。
- parallelStream() − 为集合创建并行流。
Foreach
List<String> list = Arrays.asList("zhangsan", "", "lisi");
list.stream().forEach(System.out::println);
Map和Filter(映射和过滤操作)
List<String> collect = list.stream()
.filter(x -> "lisi".equals(x))
.map(x ->x.toUpperCase())
.collect(Collectors.toList());
collect.stream().forEach(System.out::println);
Sorted排序
Random random = new Random();
random.ints().limit(20).sorted().forEach(System.out::println);
parallelStream 并行流操作
List<String> strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");
// 获取空字符串的数量
long count = strings.parallelStream().filter(string -> string.isEmpty()).count();
Lambda表达式
- Lambada允许将一个函数作为方法的参数,使用Lambada可以将代码变得简洁。
遍历List集合
1.使用Lambada表达式类似与forEach
List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(2);
//froEace循环
for (Integer ret : list) {
System.out.println(ret);
}
//使用Lambada表达式输出
list.stream().forEach(x -> System.out.println(x));
list.stream().filter(x -> x % 2 == 0).forEach(x -> System.out.println(x));
2.操作Map
@Test
public void test1() {
List<HashMap<String, String>> list = new ArrayList<>();
for (int i = 0; i < 10; i++) {
HashMap<String, String> map = new HashMap<>();
map.put(String.valueOf("键" + i), String.valueOf(i));
list.add(map);
}
//遍历HashMap得到其中的键
list.stream().forEach(x -> {
for (String y : x.keySet()) {
System.out.println("输出的值为:" + y);
}
});
//遍历HashMap得到其中的值
list.stream().forEach(x -> {
for (Map.Entry y : x.entrySet()) {
System.out.println("map中的值为:" + y);
}
});
}
遍历Map
map.forEach((k, v) -> {
System.out.println(k + "====" + v);
});
创建线程
public static void main(String[] args) {
new Thread(() -> {
System.out.println("我是进程1");
}).start();
new Thread(() -> {
System.out.println("我是进程2");
}).start();
new Thread(() -> {
System.out.println("我是进程3");
}).start();
}
List转Map
@Test
public void test3() {
List<Person> list = new ArrayList<>();
for (int i = 0; i < 10; i++) {
Person person = new Person("Person" + i, String.valueOf(i));
list.add(person);
}
Map<String, String> collect = list.stream().collect(Collectors.toMap(Person::getKey, Person::getValue));
System.out.println(collect);
}
Map转List
@Test
public void test2() {
HashMap<String, String> map = new HashMap<>();
for (int i = 0; i < 10; i++) {
map.put(String.valueOf("键" + i), String.valueOf(i));
}
System.out.println(map);
//Map转List
List<Person> collect = map.entrySet()
.stream()
.map(x -> new Person(x.getKey(), x.getValue()))
.collect(Collectors.toList());
for (Person x : collect) {
System.out.println(x.getKey() + "====" + x.getValue());
}
map.forEach((k, v) -> {
System.out.println(k + "====" + v);
});
}
Map过滤
@Test
public void test6(){
Map<String,String> map=new HashMap();
map.put("1","3");
map.put("1","1");
map.put("3","4");
map.put("4","6");
Map<String, String> collect = map.entrySet().stream().filter(x -> String.valueOf(x.getKey()).equals("1")).collect(Collectors.toMap(x -> x.getKey(), x -> x.getValue()));
System.out.println(collect);
}