将List <pair <a,b >>制成列表<a> , List<b> in java

时间:2018-07-21 20:49:09

标签: java list

I have a List(Pair(a,b)), i want to extract all b element and put them in one list( List(b)) what is the best way?

1 个答案:

答案 0 :(得分:1)

这是Java 9:

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) {
        List<Map.Entry<String, String>> list = Arrays.asList(
                Map.entry("a", "b"),
                Map.entry("a", "b"),
                Map.entry("a", "b")
        );
        System.out.println(list);
        List<String> result = list.stream().map(Map.Entry::getValue).collect(Collectors.toList());
        System.out.println(result);
    }
}