從集合中取出某些屬性組成新的集合的幾種方法
比如我們有一個裝有學生類的集合,我們想獲得所有學生的姓名組成的一個新的集合
1,準備工作
爲了進行測試,首先,我們需要定義一個實體類
package com.me;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Student {
private String name;
private Integer age;
}
2,獲取新集合的方法
2.1下面使用第一種方法獲取,利用流的思想,用到了forEach方法
package com.me;
import org.junit.Test;
import java.util.ArrayList;
public class ListDemoOne {
@Test
public void test(){
ArrayList<Student> list = new ArrayList<>();
Student one = new Student("一", 1);
Student two = new Student("二", 2);
Student three = new Student("三", 3);
list.add(one);
list.add(two);
list.add(three);
ArrayList<String> nameList = new ArrayList<>();
list.forEach(s -> nameList.add(s.getName()));
System.out.println(nameList);
}
}
2.2使用第二種方法獲取,同樣利用流的思想,不過這次使用的是map和collect方法
package com.me;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class ListDemoTwo {
@Test
public void test(){
ArrayList<Student> list = new ArrayList<>();
Student one = new Student("一", 1);
Student two = new Student("二", 2);
Student three = new Student("三", 3);
list.add(one);
list.add(two);
list.add(three);
List<String> nameList = list.stream().map(Student::getName).collect(Collectors.toList());
System.out.println(nameList);
}
}
2.3使用第三種方法獲取,這次用的是Spring提供的工具類CollectionUtils下的transform方法
package com.me;
import org.junit.Test;
import org.springframework.cglib.core.CollectionUtils;
import java.util.ArrayList;
import java.util.List;
public class ListDemoThree {
@Test
public void test(){
ArrayList<Student> list = new ArrayList<>();
Student one = new Student("一", 1);
Student two = new Student("二", 2);
Student three = new Student("三", 3);
list.add(one);
list.add(two);
list.add(three);
//這裏的參數s是Object類型,需要進行強轉才能調用getName方法
List<String> nameList = CollectionUtils.transform(list, s -> ((Student) s).getName());
System.out.println(nameList);
}
}
3,總結
這三種方法都可以達到我們想要的結果,但是第二種和第三種方法省去了我們new新集合對象的過程,更爲方便一些。