简体   繁体   中英

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.

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:

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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