2017-10-16 45 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 + 
       '}'; 
    } 
}