@HUST-SuWB
2018-04-22T07:11:24.000000Z
字数 4480
阅读 350
Finlabtech
Java8其实已经发布很久了,只是在前公司的时候,组里的主流版本还是1.7,换了公司后,因为这边主要还是创业氛围,所以技术选型方面自由度会高一些,所以Java版本也就顺便一起升级到了1.8。
Java8的几个重点更新:Stream、lambda表达式以及函数式编程。我在网上看到过一篇示例介绍觉得还不错,推荐一下:Java8 lambda表达式10个示例。在这里我也贴一下我自己练习的一些例子,以供参考。
首先,开发过程中很实用的Stream。当你开发的系统足够多以后,你肯定会发现我们对集合的使用简直是无处不在的,而对于集合的遍历又是使用中非常常见的一种姿势。那么Stream简直是遍历集合的神器,可以说大部分常见的集合遍历操作都可以由老版本Java中的for循环切换成Java8中的Stream。下面看几个例子:
/**
* 当把一个数据结构包装成 Stream 后,就要开始对里面的元素进行各类操作了。常见的操作可以归类如下。
* Intermediate:map (mapToInt, flatMap 等)、 filter、 distinct、 sorted、 peek、 limit、 skip、 parallel、 sequential、 unordered
* Terminal:forEach、 forEachOrdered、 toArray、 reduce、 collect、 min、 max、 count、 anyMatch、 allMatch、 noneMatch、 findFirst、 findAny、 iterator
* Short-circuiting:anyMatch、 allMatch、 noneMatch、 findFirst、 findAny、 limit
*/
public void createStream() {
Stream<String> stringStream = Stream.of(new String[]{"diuhbJNJ", "HHNJKyguyfyjIHI"});
// stringStream.filter(p->p.length()>10).map(String::toUpperCase).forEach(System.out::println);
List<String> result = stringStream.parallel().filter(p->p.length()>10).map(String::toUpperCase).collect(Collectors.toList());
result.forEach(System.out::println);
// String[] result = stringStream.filter(p->p.length()<10).map(String::toLowerCase).toArray(String[]::new);
}
public void operator() {
Integer[] origin = new Integer[]{1,123,415,624,6171,823,367,32,67,8,1,14157,894904,41,426};
//List<Integer> input = Arrays.asList(origin) 这种方式得到的List无法继续add数据
//List<Integer> input = new ArrayList<>(Arrays.asList(origin)); 这种方式是比较合理的数组转集合的方式
List<Integer> input = Arrays.stream(origin).collect(Collectors.toList());
input.add(21344);
// int random = input.parallelStream().mapToInt(p->p).limit(8).sum();
// System.out.println(random);
Stream<Integer> integerStream = input.stream();
Optional<Integer> max = integerStream.limit(8).max((o1, o2) -> o1 - o2);
if(max.isPresent()) {
System.out.println(max.get());
}
max = integerStream.limit(20).max((o1, o2) -> o1 - o2);
if(max.isPresent()) {
System.out.println(max.get());
}
}
public void flatMap() {
Stream<List<Integer>> inputStream = Stream.of(
Arrays.asList(14),
Arrays.asList(21, 63),
Arrays.asList(4, 5, 46)
);
Stream<Integer> outputStream = inputStream.flatMap((childList) -> childList.stream());
outputStream.peek(p->System.out.println("各内容增加8后的值为: " + (p+8))).sorted().forEach(System.out::println);
}
public void filter() {
Integer[] sixNums = {1, 2, 3, 4, 5, 6};
Integer[] evens = Arrays.stream(sixNums).filter(n -> n%2 == 0).toArray(Integer[]::new);
Stream.of(evens).forEach(System.out::println);
}
public void merge() {
Map<String, Integer> pageVisits = new HashMap<>();
String page = "https://agiledeveloper.com";
incrementPageVisit(pageVisits, page);
incrementPageVisit(pageVisits, page);
Optional<Integer> max = pageVisits.values().stream().max((o1, o2) -> o1 - o2);
if(max.isPresent()) {
System.out.println(max);
}
}
private void incrementPageVisit(Map<String, Integer> pageVisits, String page) {
pageVisits.merge(page, 1, (oldValue, value) -> oldValue + value);
}
public void other() {
List<String> names = Arrays.asList("Jack", "Jill", "Nate", "Kara", "Kim", "Jullie", "Paul", "Peter");
names.forEach(System.out::println);
String output = names.stream()
.filter(name -> name.length() == 4)
.collect(Collectors.joining(", "));
output += names.stream()
.filter(this::ifMatch)
.collect(Collectors.joining(", "));
System.out.println(output);
}
public void reduce() {
List<Integer> costBeforeTax = Arrays.asList(100, 200, 300, 400, 500);
double bill = costBeforeTax.stream().map((cost) -> cost + 0.12f*cost).reduce((sum, cost) -> sum + cost).get();
System.out.println("Total : " + bill);
}
private boolean ifMatch(String s) {
return true;
}
然后,在Java中还有一种很常见的使用姿势可以被lambda表达式取代,那就是匿名类。这里贴一下上面提到的那篇文章里的例子:
// Java 8之前:
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("Before Java8, too much code for too little to do");
}
}).start();
//Java 8方式:
new Thread( () -> System.out.println("In Java8, Lambda expression rocks !!") ).start();
最后,关于函数式编程,其实通俗解释就是函数本身可以作为函数的入参,也贴个例子:
public void filterFunction() {
List<String> languages = Arrays.asList("Java", "Scala", "C++", "Haskell", "Lisp");
System.out.println("Languages which starts with J :");
filter(languages, (str)->str.startsWith("J"));
System.out.println("Languages which ends with a ");
filter(languages, (str)->str.endsWith("a"));
System.out.println("Print all languages :");
filter(languages, (str)->true);
System.out.println("Print no language : ");
filter(languages, (str)->false);
System.out.println("Print language whose length greater than 4:");
filter(languages, (str)->str.length() > 4);
}
private void filter(List<String> names, Predicate<String> condition) {
names.stream().filter(condition).forEach(System.out::println);
}
用上了Java8以后,代码看起来确实会更加的舒服,也会更加简洁。当然,现在Java的更新频率调整了,以后每半年一个版本,我现在连Java9的模块化编程都没见过,Java10都快出来了。得逼着自己紧跟时代步伐啊,不然就要变成老古董了。