一、关于jdk8对接口的新定义
增加了默认的方法
增加了静态的方法
二、对于lambda表达式,必须要有其上下文,才能推断其类型
package cn.org.kingdom.jdk8;
public class Test3 {
public static void main(String[] args) {
TheInterface i1 = ()->{};
System.out.println(i1.getClass().getInterfaces()[0]);
TheInterface2 i2 = ()->{};
System.out.println(i2.getClass().getInterfaces()[0]);
/*
* ()->{};的类型必须依靠其上下文
*/
new Thread(()->{
System.out.println("执行线程操作");
}).start();
}
}
@FunctionalInterface
interface TheInterface{
public void method();
}
@FunctionalInterface
interface TheInterface2{
public void method2();
}
三、接下来看一个案例:要求对一个集合里的字符串的小写改为大写
List<String> list = Arrays.asList("hello","world","sky","moon");
List<String> list2 = new ArrayList<String>();
list.forEach((e)->{
//先放入到list2
list2.add(e.toUpperCase());
});
list2.forEach(e->System.out.println(e));
对于以上代码并没有得到太多的简化,逻辑上与我们之前的代码逻辑差不多,下面我们采用流的方式来编写,首先来观察一下Collection接口中的方法
/**
* Returns a sequential {@code Stream} with this collection as its source.
*
* <p>This method should be overridden when the {@link #spliterator()}
* method cannot return a spliterator that is {@code IMMUTABLE},
* {@code CONCURRENT}, or <em>late-binding</em>. (See {@link #spliterator()}
* for details.)
*
* @implSpec
* The default implementation creates a sequential {@code Stream} from the
* collection's {@code Spliterator}.
*
* @return a sequential {@code Stream} over the elements in this collection
* @since 1.8
*/
default Stream<E> stream() {
return StreamSupport.stream(spliterator(), false);
}
/**
* Returns a possibly parallel {@code Stream} with this collection as its
* source. It is allowable for this method to return a sequential stream.
*
* <p>This method should be overridden when the {@link #spliterator()}
* method cannot return a spliterator that is {@code IMMUTABLE},
* {@code CONCURRENT}, or <em>late-binding</em>. (See {@link #spliterator()}
* for details.)
*
* @implSpec
* The default implementation creates a parallel {@code Stream} from the
* collection's {@code Spliterator}.
*
* @return a possibly parallel {@code Stream} over the elements in this
* collection
* @since 1.8
*/
default Stream<E> parallelStream() {
return StreamSupport.stream(spliterator(), true);
}
使用stream的方式改写
List<String> list = Arrays.asList("hello", "world", "sky", "moon");
list.stream().map(item -> item.toUpperCase())
.forEach(item -> System.out.println(item));
System.out.println("=================");
list.stream().map(String::toUpperCase).forEach(e->System.out.println(e));