Java8学习笔记(八)--方法引入的补充
在Java8学习笔记(三)--方法引入中,简要总结了方法引入时的使用规则,但不够完善。这里补充下几种情况:
从形参到实例方法的实参
示例
public class Example {
static List<Integer> intList = Arrays.asList(1,2,3,4);
public String increment(int i)
{
return String.valueOf(++i);
}
@Test
public void testLambda()
{
//.map(this::increment)<=>.map(i->example.increment(i))...
intList.stream().map(this::increment).forEach(System.out::println);
}
}
从形参到目标
示例
Stream.of("a","b").map(String::toUpperCase).forEach(System.out::println);
从形参到构造函数实参
示例
static List<String> strList = Arrays.asList("a","b","c","d");
//.map(String::new) <=> str->new String(str)
strList.stream().map(String::new).forEach(System.out::println);
传递两个形参作为实参
示例
List<Integer> intList = Arrays.asList(1,2,3,4);
//Integer::sum <=> (a,b)->Integer.sum(a,b)
int i =intList.stream().reduce(Integer::sum).get();
System.out.println(i);
第一个形参作为调用的目标而传递
示例
//String::concat <=> (a,b)->a.concat(b)
Stream.of("a","b").reduce("",String::concat);
原文
God, Grant me the SERENITY, to accept the things I cannot change,
COURAGE to change the things I can, and the WISDOM to know the difference.