获取List <object []>的所有第一个值

时间:2017-10-16 15:03:54

标签: java

我有清单:

List<Object[]> list;

在这个列表中我有结构:

list.get(0) returns ("dog", 11)  
list.get(1) returns ("cat", 22)  
etc.

如何使用lambda表达式只检索宠物类型?我想要一个仅包含“dog”,“cat”等的新列表,

2 个答案:

答案 0 :(得分:2)

一种简单的方法是使用流api:

List firstElements = list.stream().map(o -> o[0]).collect(Collectors.toList());

答案 1 :(得分:0)

就像使用mapcollect一样简单。

private void test(String[] args) {
    List<Animal> list = new ArrayList<>();
    list.add(new Animal("dog",11));
    list.add(new Animal("cat",22));
    List<String> names = list.stream()
            // Animal -> animal.type.
            .map(a -> a.getType())
            // Collect into a list.
            .collect(Collectors.toList());
    System.out.println(names);
}

我使用Animal作为:

class Animal {
    final String type;
    final int age;

    public Animal(String type, int age) {
        this.type = type;
        this.age = age;
    }

    public String getType() {
        return type;
    }

    public int getAge() {
        return age;
    }

    @Override
    public String toString() {
        return "Animal{" +
                "type='" + type + '\'' +
                ", age=" + age +
                '}';
    }
}
相关问题