Java 8 函数式编程(4)

本篇对应《Java 8 函数式编程》第 5 章。


要点回顾

  1. 方法 引用 是一 种 引用 方法 的 轻量级 语法, 形如: ClassName:: methodName。
  2. 收集 器 可用 来 计算 流的 最 终值, 是 reduce 方法 的 模拟。
  3. Java 8 提供 了 收集 多种 容器 类型 的 方式, 同时 允许 用户 自定义 收集器。

练习

Question 1:

https://leetcode.com/playground/KrzQMGgR

public static void subquestionA() {
        List<String> collected = Stream.of("a", "b", "hello")
                                       .map(String::toUpperCase)
                                       .collect(Collectors.toList());
        System.out.println(collected);
    }
    
    public static void subquestionB() {
        int count = Stream.of(1, 2, 3)
                          .reduce(0, Integer::sum);
        System.out.println(count);
    }
    
    public static void subquestionC() {
        List<Integer> together = Stream.of(Arrays.asList(1,2), Arrays.asList(3,4))
                                       .flatMap(List::stream)
                                       .collect(Collectors.toList());
        System.out.println(together);
    }

Question 2:

LongestName.java

public class LongestName {

    private static Comparator<Artist> byNameLength = comparing(artist -> artist.getName().length());

    public static Artist byReduce(List<Artist> artists) {
        return artists.stream()
                      .reduce((acc, artist) -> {
                          return (byNameLength.compare(acc, artist) >= 0) ? acc : artist;
                      })
                      .orElseThrow(RuntimeException::new);
    }

    public static Artist byCollecting(List<Artist> artists) {
        return artists.stream()
                      .collect(Collectors.maxBy(byNameLength))
                      .orElseThrow(RuntimeException::new);
    }

}

WordCount.java

public class WordCount {

    public static Map<String, Long> countWords(Stream<String> names) {
        return names.collect(groupingBy(name -> name, counting()));
    }

}

GroupingBy.java

public class GroupingBy<T, K> implements Collector<T, Map<K, List<T>>, Map<K, List<T>>> {

    private final static Set<Characteristics> characteristics = new HashSet<>();
    static {
        characteristics.add(Characteristics.IDENTITY_FINISH);
    }

    private final Function<? super T, ? extends K> classifier;

    public GroupingBy(Function<? super T, ? extends K> classifier) {
        this.classifier = classifier;
    }

    @Override
    public Supplier<Map<K, List<T>>> supplier() {
        return HashMap::new;
    }

    @Override
    public BiConsumer<Map<K, List<T>>, T> accumulator() {
        return (map, element) -> {
            K key = classifier.apply(element);
            List<T> elements = map.computeIfAbsent(key, k -> new ArrayList<>());
            elements.add(element);
        };
    }

    @Override
    public BinaryOperator<Map<K, List<T>>> combiner() {
        return (left, right) -> {
            right.forEach((key, value) -> {
                left.merge(key, value, (leftValue, rightValue) -> {
                    leftValue.addAll(rightValue);
                    return leftValue;
                });
            });
            return left;
        };
    }

    @Override
    public Function<Map<K, List<T>>, Map<K, List<T>>> finisher() {
        return map -> map;
    }

    @Override
    public Set<Characteristics> characteristics() {
        return characteristics;
    }

}

Question 3:

Fibonacci.java

public class Fibonacci {

    private final Map<Integer,Long> cache;

    public Fibonacci() {
        cache = new HashMap<>();
        cache.put(0, 0L);
        cache.put(1, 1L);
    }

    public long fibonacci(int x) {
        return cache.computeIfAbsent(x, n -> fibonacci(n-1) + fibonacci(n-2));
    }

}

参考:

71 total views, no views today

Java 8 函数式编程(3)

本篇对应《Java 8 函数式编程》的第四章。


要点回顾

  1. 使用为基本类型定制的Lambda表达式和Stream,如IntStream可以显著提升系统性能。
  2. 默认方法是指接口中定义的包含方法体的方法,方法名有default关键字做前缀。
  3. 在一个值可能为空的建模情况下,使用Optional对象能替代使用null值。

练习

Question 1:

/** 该接口表示艺术家的演出——专辑或演唱会 */
public interface Performance {

    public String getName();

    public Stream<Artist> getMusicians();

    public default Stream<Artist> getAllMusicians() {
        return getMusicians()
              .flatMap(artist -> concat(Stream.of(artist), artist.getMembers()));
    }

}

Question2:

不能。

public interface Parent {
    default public boolean equals(Object object) {
        return true;
    }

    default public int hashCode() {
        return 1;
    }
}
% javac Parent.java
Parent.java:2: error: default method equals in interface Parent overrides a member of java.lang.Object
    default public boolean equals(Object object) {
                           ^
Parent.java:6: error: default method hashCode in interface Parent overrides a member of java.lang.Object
    default public int hashCode() {
                       ^
2 errors

Question 3:

public class Artists {

    private List<Artist> artists;

    public Artists(List<Artist> artists) {
        this.artists = artists;
    }

    public Optional<Artist> getArtist(int index) {
        if (index < 0 || index >= artists.size()) {
            return Optional.empty();
        }
        return Optional.of(artists.get(index));
    }

    public String getArtistName(int index) {
        Optional<Artist> artist = getArtist(index);
        return artist.map(Artist::getName)
                     .orElse("unknown");
    }

}

参考:

163 total views, no views today

Java 8 函数式编程(2)

本篇对应《Java 8 函数式编程》的第三章。

PS:如果你还没有了解过 Iterator 设计模式,请先去了解一下 Iterator 设计模式


Stream

Stream 是用函数式编程方式在集合类上进行复杂操作的工具。

int sum = widgets.stream()
                 .filter(w -> w.getColor() == RED)
                 .mapToInt(w -> w.getWeight())
                 .sum();

比如这个官方文档上的代码示例:计算所有红色 Widget 的权重的总和。

  1. 使用 Collection.stream() 方法,创建 widgets 集合的流。
  2. 使用 filter 操作,产生一个只包含红色 widgets 的流。
  3. 使用 mapToInt 操作,转换成红色 widgets 的权重的流。
  4. 使用 sum 操作,计算红色 widgets 的权重之和。

Stream operations and pipelines

流操作(Stream operations)分为中间操作(intermediate operations)和终点操作(terminal operations),合在一起就形成了流管道(stream pipelines)。

一个流管道(stream pipelines)包含一个数据源(source),零到多个中间操作(intermediate operations)和一个终点操作(terminal operations)。

数据源(source)可以是一个数组,一个集合,一个生成函数,一个 I/O 通道,~。

中间操作(intermediate operations)就是把一个流转换成另外一个流,比如 filter 和 map。

终点操作(terminal operations)会产生一个结果或者副作用,比如 count 和 forEach。

流是惰性求值的,只有终点操作(terminal operations)开始的时候,所有数据源(source)上的计算才会真正被执行,并且数据源元素只在需要时才会被使用。

常用的流操作

filterintermediate operationstateless
map
mapToInt
mapToLong
mapToDouble
flatMap
flatMapToInt
flatMapToLong
flatMapToDouble
distinctstateful
sorted
peek
limit
skip
takeWhile
dropWhile
forEachterminal operation
forEachOrdered
toArray
reduce
collect
max
count
anyMatch
allMatch
noneMatch
findFirst
findAny

练习

Question 1:

    public static int addUp(Stream<Integer> numbers) {
        return numbers.reduce(0, (acc, x) -> acc + x);
    }

    public static List<String> getNamesAndOrigins(List<Artist> artists) {
        return artists.stream()
                      .flatMap(artist -> Stream.of(artist.getName(), artist.getNationality()))
                      .collect(toList());
    }

    public static List<Album> getAlbumsWithAtMostThreeTracks(List<Album> input) {
        return input.stream()
                    .filter(album -> album.getTrackList().size() <= 3)
                    .collect(toList());
    }

Question 2:

int totalMembers = (int) artists.stream().flatMap(artist -> artist.getMembers()).count();

Question 3:

a. 及早求值(Eager)- 返回 Stream
b. 惰性求值(Lazy)

Question 4:

a. 是 - 参数是函数
b. 否

Question 5:

a. 没有副作用

Question 6:

    public static int countLowercaseLetters(String string) {
        return (int) string.chars()
                           .filter(Character::isLowerCase)
                           .count();
    }

Question 7:

    public static Optional<String> mostLowercaseString(List<String> strings) {
        return strings.stream()
                      .max(Comparator.comparing(StringExercises::countLowercaseLetters));
    }

进阶练习

Question 1:

import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Stream;

/**
 * Advanced Exercises Question 1
 */
public class MapUsingReduce {

    public static <I, O> List<O> map(Stream<I> stream, Function<I, O> mapper) {
        return stream.reduce(new ArrayList<O>(), (acc, x) -> {
        	// We are copying data from acc to new list instance. It is very inefficient,
        	// but contract of Stream.reduce method requires that accumulator function does
        	// not mutate its arguments.
        	// Stream.collect method could be used to implement more efficient mutable reduction,
        	// but this exercise asks to use reduce method.
        	List<O> newAcc = new ArrayList<>(acc);
        	newAcc.add(mapper.apply(x));
            return newAcc;
        }, (List<O> left, List<O> right) -> {
        	// We are copying left to new list to avoid mutating it. 
        	List<O> newLeft = new ArrayList<>(left);
        	newLeft.addAll(right);
            return newLeft;
        });
    }

}

Question 2:

import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Stream;

/**
 * Advanced Exercises Question 2
 */
public class FilterUsingReduce {

    public static <I> List<I> filter(Stream<I> stream, Predicate<I> predicate) {
        List<I> initial = new ArrayList<>();
        return stream.reduce(initial,
                             (List<I> acc, I x) -> {
                                if (predicate.test(x)) {
                                	// We are copying data from acc to new list instance. It is very inefficient,
                                	// but contract of Stream.reduce method requires that accumulator function does
                                	// not mutate its arguments.
                                	// Stream.collect method could be used to implement more efficient mutable reduction,
                                	// but this exercise asks to use reduce method explicitly.
                                	List<I> newAcc = new ArrayList<>(acc);
                                    newAcc.add(x);
                                    return newAcc;
                                } else {
                                	return acc;
                                }
                             },
                             FilterUsingReduce::combineLists);
    }

    private static <I> List<I> combineLists(List<I> left, List<I> right) {
    	// We are copying left to new list to avoid mutating it. 
    	List<I> newLeft = new ArrayList<>(left);
    	newLeft.addAll(right);
        return newLeft;
    }

}

参考:

https://www.ibm.com/developerworks/cn/java/j-lo-java8streamapi/

https://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html

154 total views, no views today

Java 8 函数式编程 (1)

本篇对应《Java 8 函数式编程》的第一章和第二章。


什么是函数式编程

面向对象编程是对数据进行抽象,而函数式编程是对行为进行抽象。

每个人对函数式编程的理解不尽相同。但其核心是:在思考问题时,使用不可变值和函数,函数对一个值进行处理,映射成另一个值。


Lamda 表达式

Lambda 允许把函数作为一个方法的参数(函数作为参数传递进方法中)。

lambda 表达式的语法格式如下:

(parameters) -> expression
或
(parameters) ->{ statements; }

Lambda 表达式的简单例子:

// 1. 不需要参数,返回值为 5  
() -> 5  
  
// 2. 接收一个参数(数字类型),返回其2倍的值  
x -> 2 * x  
  
// 3. 接受2个参数(数字),并返回他们的差值  
(x, y) -> x – y  
  
// 4. 接收2个int型整数,返回他们的和  
(int x, int y) -> x + y  
  
// 5. 接受一个 string 对象,并在控制台打印,不返回任何值(看起来像是返回void)  
(String s) -> System.out.print(s)

有一点需要注意的是:

Lambda表达式中引用的局部变量必须是final或既成事实上的final变量。


函数式接口

在介绍 Functional Interface 之前,我们先来了解一下另外一个概念(first-class functions)。

In computer science, a programming language is said to have first-class functions if it treats functions as first-class citizens. This means the language supports passing functions as arguments to other functions, returning them as the values from other functions, and assigning them to variables or storing them in data structures.

这一段话并不难理解,函数是一等公民,一等公民什么都可以做。

  1. 函数可以作为其他函数的参数。
  2. 函数可以作为其他函数的返回值。
  3. 函数可以赋值给变量,可以存储在数据结构中。

为什么要在介绍函数式接口之前先介绍这些呢,因为 函数为第一公民是函数式编程的基础。而 Java 语言的函数显然是不具备这个基础的,所以便有了函数式接口。

只包含一个抽象方法的接口,称为 函数式接口(Functional Interface)。

比如 Consumer 接口,只有一个抽象方法 void accept(T t),参数 T,没有返回值。

package java.util.function;

import java.util.Objects;

/**
 * Represents an operation that accepts a single input argument and returns no
 * result. Unlike most other functional interfaces, {@code Consumer} is expected
 * to operate via side-effects.
 *
 * <p>This is a <a href="package-summary.html">functional interface</a>
 * whose functional method is {@link #accept(Object)}.
 *
 * @param <T> the type of the input to the operation
 *
 * @since 1.8
 */
@FunctionalInterface
public interface Consumer<T> {

    /**
     * Performs this operation on the given argument.
     *
     * @param t the input argument
     */
    void accept(T t);

    /**
     * Returns a composed {@code Consumer} that performs, in sequence, this
     * operation followed by the {@code after} operation. If performing either
     * operation throws an exception, it is relayed to the caller of the
     * composed operation.  If performing this operation throws an exception,
     * the {@code after} operation will not be performed.
     *
     * @param after the operation to perform after this operation
     * @return a composed {@code Consumer} that performs in sequence this
     * operation followed by the {@code after} operation
     * @throws NullPointerException if {@code after} is null
     */
    default Consumer<T> andThen(Consumer<? super T> after) {
        Objects.requireNonNull(after);
        return (T t) -> { accept(t); after.accept(t); };
    }
}

我们可以用 Consumer 接口来写的一个 Hello,World。

import java.util.function.Consumer;

public class Main
{
    public static void echo(Consumer<String> consumer, String t) {
        consumer.accept(t);
    }

    public static void main(String[] args) {
        Consumer<String> hello = string -> System.out.println("hello, " + string);

        echo(hello, "world");
    }
}

练习

* Question 1:
* a.
* b. 一元运算符,比如负号,百分比。
* c. x -> x + 1;
*
* Question 2:
* a. N/A
* b. public final static ThreadLocal<DateFormatter> formatter = ThreadLocal.withInitial(() -> new DateFormatter(new SimpleDateFormat(“dd-MMM-yyyy”)));
*
* Question 3:
* a. Yes
* b. Yes
* c. No – the lambda expression could be inferred as IntPred or Predicate<Integer> so the overload is ambiguous.

参考:

https://www.runoob.com/java/java8-lambda-expressions.html

https://www.runoob.com/java/java8-functional-interfaces.html

https://en.wikipedia.org/wiki/First-class_function

https://kotlinlang.org/docs/reference/lambdas.html

https://www.ibm.com/developerworks/cn/java/j-understanding-functional-programming-3/

223 total views, no views today