如何使用流从自定义 class 中提取字段? (不使用 for/while 循环)

How do I pull out fields from a custom class using streams? (Without using for/while loops)

I would like to know how to pull out field and make it become a list using streams. For example, if I have a list of Pairs, Pair[2] { Pair<3,5>,Pair<5,7>}, I would like to make it become Integer[3] {3,5,7}. (After using Stream.distinct() to remove the dupicate 5) Pair class is provided if that is needed.

public class Pair<T,U> {
    private final T first;
    private final U second;

    public Pair(T first, U second){
        this.first = first;
        this.second = second;
    }

    T first() {
        return this.first;
    }

    U second(){
        return this.second;
    }

    @Override
    public String toString(){
        return "<" + this.first + ", "+ this.second+">";
    }
}

您想将成对流变成数字流;为此,任何给定的对都被映射到流中可变数量的项目中。 .map 只能将一件事映射到另一件事。 flatMap,另一方面,可以将一个事物映射到任意数量(甚至0)的事物。

flatMap 将流的一个元素转换为您想要的任何流 - 然后将这些流连接在一起形成一个新的单个流。

因此,您需要做的就是将一个 Pair<Integer, Integer> 实例转换为表示 2 个整数的流。 Java 将完成剩下的工作:

pairs.stream().flatMap(pair -> Stream.of(p.first(), p.second())).distinct().forEach(System.out::println);

最终会根据需要打印 3、5 和 7。

注意:对 java 风格不好。 Java 是广泛的名义:它是围绕事物命名的概念设计的。这些数字对代表比 'a pair of numbers' 更具体的东西。你应该制作一个 class 来模拟那个确切的东西。另一种方法是,我们取消 Person class 并创建 Tuple<String, Tuple<Integer, Integer, Integer>, String> 而不是带有字段 String name; 的 class,LocalDate birthDate;String studentId; 等等。显然是个坏主意。