Lambdas 和 Streams

2018-02-07  本文已影响0人  李军_6eaa
Java 8 的新特性,有哪些?
解释一下 function types
解释一下 function objects
解释一下 functional interfaces
在创建函数对象时,为什么优先使用lambdas,而不使用匿名类
举几个例子,说明Lambdas比匿名类好用
Collections.sort(words, new Comparator<String>() {
    public int compare(String s1, String s2) {
        return Integer.compare(s1.length(), s2.length());
    }
});
Collections.sort(words,
        (s1, s2) -> Integer.compare(s1.length(), s2.length()));
Collections.sort(words, comparingInt(String::length));
words.sort(comparingInt(String::length));
使用Lambdas的注意事项
什么时候只能使用匿名类,而不能使用lambdas
为什么优先使用method references,而不是lambdas
map.merge(key, 1, (count, incr) -> count + incr);
map.merge(key, 1, Integer::sum);
service.execute(GoshThisClassNameIsHumongous::action);

等价于

service.execute(() -> action());

相似地,

Function.identity()

等价于

x -> x
有哪几种方法引用?
Integer::parseInt

对应的Lambda

str -> Integer.parseInt(str)
Instant.now()::isAfter

对应的Lambda

Instant then = Instant.now(); 
t -> then.isAfter(t)
String::toLowerCase

对应的Lambda

str -> str.toLowerCase()
TreeMap<K,V>::new

对应的Lambda

() -> new TreeMap<K,V>
int[]::new

对应的Lambda

len -> new int[len]
优先使用 standard functional interfaces, 说说你对java.util.function.Function中的函数接口的了解
Interface Function Signature Example
UnaryOperator<T> T apply(T t) String::toLowerCase
BinaryOperator<T> T apply(T t1, T t2) BigInteger::add
Predicate<T> boolean test(T t) Collection::isEmpty
Function<T,R> R apply(T t) Arrays::asList
Supplier<T> T get() Instant::now
Consumer<T> void accept(T t) System.out::println
在使用Streams API时,应该注意什么?
在流中,如何使用无副作用的函数
Map<String, Long> freq = new HashMap<>();
try (Stream<String> words = new Scanner(file).tokens()) {
    words.forEach(word -> {
        freq.merge(word.toLowerCase(), 1L, Long::sum);
    });
}
Map<String, Long> freq;
try (Stream<String> words = new Scanner(file).tokens()) {
    freq = words
        .collect(groupingBy(String::toLowerCase, counting()));
} 
List<String> topTen = freq.keySet().stream()
    .sorted(comparing(freq::get).reversed())
    .limit(10)
    .collect(toList());
private static final Map<String, Operation> stringToEnum =
    Stream.of(values()).collect(
        toMap(Object::toString, e -> e));
Map<Artist, Album> topHits = albums.collect(
   toMap(Album::artist, a->a, maxBy(comparing(Album::sales))));

Collector to impose last-write-wins policy

toMap(keyMapper, valueMapper, (v1, v2) -> v2)
words.collect(groupingBy(word -> alphabetize(word)))
Map<String, Long> freq = words
        .collect(groupingBy(String::toLowerCase, counting()));
为了同时提供使用 iteration 和 stream 的功能,应该优先使用Collection作为返回类型,而不是Stream
谨慎使用streams parallel,在使用时应该注意的问题
上一篇 下一篇

猜你喜欢

热点阅读