为什么选择 Java 8 ?(为什么选择教师这个职业)

网友投稿 588 2022-09-12

本站部分文章、图片属于网络上可搜索到的公开信息,均用于学习和交流用途,不能代表睿象云的观点、立场或意见。我们接受网民的监督,如发现任何违法内容或侵犯了您的权益,请第一时间联系小编邮箱jiasou666@gmail.com 处理。

为什么选择 Java 8 ?(为什么选择教师这个职业)

要点速递

让我们来了解一下 Java8 的一些特性,让你在说服团队升级 Java 版本时理由能更充分一些。

速度更快

可以取悦老板、满足业务或运营人员的一大卖点是:Java8 运行应用时速度更快。通常,升级至 Java8 的应用都能得到速度上的提升,即便没有做任何改变或调优。对于为了迎合特定 JVM 而做出调整的应用,这或许并不适用。但 Java8 性能更优的理由还有很多:

代码行更少

Java 经常被人们诟病其样本代码太多。为此,Java8 新的 API 采用了更具功能性的方式,专注于实现什么而不是如何实现。

Lambda 表达式

集合新方法介绍

private final Map customers = new HashMap<>();public void incrementCustomerOrders(CustomerId customerId) {Customer customer = customers.get(customerId);if (customer == null) { customer = new Customer(customerId); customers.put(customerId, customer);}customer.incrementOrders();}

操作“检查某个成员在 map 中是否存在,若不存在则添加之”是如此常用,Java 现在为 Map 添加了一个新方法 computeIfAbsent 来支持这个操作。该方法的第二个参数是一个 Lambda 表达式,该表达式定义了如何创建缺少的成员。

public void incrementCustomerOrders(CustomerId customerId) {Customer customer = customers.computeIfAbsent(customerId, id -> new Customer(id));customer.incrementOrders();}

public void incrementCustomerOrders(CustomerId customerId) {Customer customer = customers.computeIfAbsent(customerId, Customer::new);customer.incrementOrders();}

Java8 为 Map 与 List 都添加了新方法。你可以了解一下这些新方法,看它们能节省多少行代码。

Streams API

public List getAllAuthorsAlphabetically(List books) {List authors = new ArrayList<>();for (Book book : books) { Author author = book.getAuthor(); if (!authors.contains(author)) { authors.add(author); }}Collections.sort(authors, new Comparator() { public int compare(Author o1, Author o2) { return o1.getSurname().compareTo(o2.getSurname()); }});return authors;}

public List getAllAuthorsAlphabetically(List books) {return books.Streams() .map(book -> book.getAuthor()) .distinct() .sorted((o1, o2) -> o1.getSurname().compareTo(o2.getSurname())) .collect(Collectors.toList());}

public List getAllAuthorsAlphabetically(List books) {return books.Streams() .map(Book::getAuthor) .distinct() .sorted(Comparator.comparing(Author::getSurname)) .collect(Collectors.toList());}

便于并行

最大化减少 Null 指针

Java8 的另一个新特性是全新的 Optional 类型。该类型的含义是“我可能有值,也可能是 null。“这样一来,API 就可以区分可能为 null 的返回值与绝对不会是 null 的返回值,从而最小化 NullPointerException 异常的发生几率。

Optional 最赞的用处是处理 null。例如,假设我们要从一个列表中找一本特定的书,新创建的 findFirst() 方法会返回 Optional 类型的值,表明它无法确保是否找到特定的值。有了这个可选择的值,我们接下来可以决定,如果是 null 值要如何处理。如果想要抛出一个自定义的异常,我们可以使用 orElseThrow:

public Book findBookByTitle(List books, String title) {Optional foundBook = books.Streams() .filter(book -> book.getTitle().equals(title)) .findFirst();return foundBook.orElseThrow(() -> new BookNotFoundException("Did not find book with title " + title));}

或者,你可以返回其他书:

return foundBook.orElseGet(() -> getRecommendedAlternativeBook(title));

或者,返回 Optional 类型,这样,该方法的调用者可以自己决定书没找到时要怎么做。

总结

上一篇:DIY Ruby CPU 分析——Part IV(diy手工制作大全)
下一篇:技术公开课:千万级并发下的数据库性能调优实践
相关文章

 发表评论

暂时没有评论,来抢沙发吧~