2017-10-16 43 views
-3

的所有第一个值我有列表:获取列表<Object[]>

List<Object[]> list; 

在这个名单上有结构:

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

我怎么只能检索使用lambda表达式宠物类型?我想只含有“狗”,“猫”等,

+4

为什么这样的非面向对象的结构? F#不是更好的匹配吗? –

+2

到目前为止您尝试了什么?看看你的列表的方法'stream()'和流中的filter(),map(),collect()等等。 – Thomas

回答

2

一个简单的方法是使用流API的新列表:

List firstElements = list.stream().map(o -> o[0]).collect(Collectors.toList()); 
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 + 
       '}'; 
    } 
}