简体   繁体   English

如何从 Java 中的元组列表中提取第 n 个元素?

[英]How to extract the n-th elements from a list of tuples in Java?

Basically I try to extract only the 2nd element from the list of tuples.基本上我尝试只从元组列表中提取第二个元素。 Scala has a very nice solution to this (which somewhat looks like this x._2) but I don't know how I can do this in Java. Scala 对此有一个非常好的解决方案(有点像 x._2),但我不知道如何在 Java 中做到这一点。

public static ArrayList<House> house = new ArrayList<>(Arrays.asList(new House(321321, 2.5),
                                                                     new House(456544, 3.0),
                                                                     new House(789687, 4.0));

Assuming your House class has getters for these values eg:假设您的House class 具有这些值的吸气剂,例如:

public class House {
    private final int value1;
    private final double value2;

    public House(final int value1, final double value2) {
        this.value1 = value1;
        this.value2 = value2;
    }

    public int getValue1() {
        return value1;
    }

    public double getValue2() {
        return value2;
    }
}

You can do a map and collect to get the second value:您可以执行 map 并收集以获取第二个值:

final List<Double> value2s = house.stream().map(House::getValue2).collect(Collectors.toList());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM