【JDK 8特性】快速將List轉爲Map、分組、過濾、求和

樂猿社區,程序員的花果山程序員

List轉Map

/**
 * List -> Map
 * 比較優雅的寫法是這樣的
 */
public static Map<Integer,User> getUser2MapUser2(List<User>userlist){
   return userlist.stream().collect(Collectors.toMap(User::getAge, Function.identity()));
}
/**
 * List -> Map
 * 重複key的狀況下 簡單的使用後者覆蓋前者的
 */
public static Map<Integer,User> getUser2MapUser3(List<User>userlist){
    return userlist.stream().collect(Collectors.toMap(User::getAge, Function.identity(),(key1,key2)->key2));
}
/**
 * List -> Map
 * 指定map的具體實現
 */
public static Map<Integer,User> getUser2MapUser4(List<User>userlist){
    return userlist.stream().collect(Collectors.toMap(User::getAge, Function.identity(),(key1,key2)->key2, LinkedHashMap::new));
}

分組

List裏面的對象元素,以某個屬性來分組,例如,以age分組,將age相同的放在一塊兒:編程

Map<Integer, List<User>> groupBy = appleList.stream().collect(Collectors.groupingBy(User::getAge));

過濾filter

從集合中過濾出來符合條件的元素:api

//過濾出符合條件的數據
List<User> filterList = userList.stream().filter(a -> a.getName().equals("張三")).collect(Collectors.toList());

求和 sum

//計算 數量
int sum = appleList.stream().mapToInt(Apple::getNum).sum();

寫在最後

有了stream api後,對於list轉換和循環方便太多了app

鼓勵把新的Java8特性引入到目前的項目中,一個長期配合的團隊以及一門古老的編程語言都須要不斷的注入新活力,不然不進則退編程語言

[]ide

相關文章
相關標籤/搜索