2、各類案例說明
多舉點例子,之後忘記了還能夠來找本身的博客,哈哈。
首先寫一個領域對象
public class Person { private Integer id; private String name; private String sex; private Integer age; //提供get,set,和滿參構造函數 }
一、map中間件相關例子
public class TestMap { public static void main(String[] args) { List<Person> persionList = new ArrayList<Person>(); persionList.add(new Person(1,"張三","男",38)); persionList.add(new Person(2,"小小","女",2)); persionList.add(new Person(3,"李四","男",65)); persionList.add(new Person(4,"王五","女",20)); persionList.add(new Person(5,"趙六","男",38)); persionList.add(new Person(6,"大大","男",65)); //一、只取出該集合中全部姓名組成一個新集合 List<String> nameList=persionList.stream().map(Person::getName).collect(Collectors.toList()); System.out.println(nameList.toString()); //二、只取出該集合中全部id組成一個新集合 List<Integer> idList=persionList.stream().mapToInt(Person::getId).boxed().collect(Collectors.toList()); System.out.println(idList.toString()); //三、list轉map,key值爲id,value爲Person對象 Map<Integer, Person> personmap = persionList.stream().collect(Collectors.toMap(Person::getId, person -> person)); System.out.println(personmap.toString()); //四、list轉map,key值爲id,value爲name Map<Integer, String> namemap = persionList.stream().collect(Collectors.toMap(Person::getId, Person::getName)); System.out.println(namemap.toString()); //五、進行map集合存放,key爲age值 value爲Person對象 它會把相同age的對象放到一個集合中 Map<Integer, List<Person>> ageMap = persionList.stream().collect(Collectors.groupingBy(Person::getAge)); System.out.println(ageMap.toString()); //六、獲取最小年齡 Integer ageMin = persionList.stream().mapToInt(Person::getAge).min().getAsInt(); System.out.println("最小年齡爲: "+ageMin); //七、獲取最大年齡 Integer ageMax = persionList.stream().mapToInt(Person::getAge).max().getAsInt(); System.out.println("最大年齡爲: "+ageMax); //八、集合年齡屬性求和 Integer ageAmount = persionList.stream().mapToInt(Person::getAge).sum(); System.out.println("年齡總和爲: "+ageAmount); } }