每日一例 | 通過(guò)stream更便捷地獲取最大值最小值……
之前我們專門分享過(guò)stream的一些比較好用的便捷操作,比如list轉(zhuǎn)map、元素過(guò)濾等,今天我們?cè)賮?lái)補(bǔ)充幾個(gè),也是比較常用的,比如獲取list中的最大值元素,獲取最最小元素。好了,話不多說(shuō),直接開(kāi)始吧。
獲取最大值
在stream誕生以前,我們?nèi)绻@取集合中的最大值,基本上都是需要循環(huán)遍歷整個(gè)元素:
private static User maxAgeUser1(List<User> userList) {
User maxAgeUser = new User();
maxAgeUser.setAge(0);
for (User user : userList) {
if (user.getAge() > maxAgeUser.getAge()) {
maxAgeUser = user;
}
}
return maxAgeUser;
}
整數(shù)
private static int maxInt1(List<Integer> integerList) {
int max = 0;
for (Integer integer : integerList) {
if (integer > max) {
max = integer;
}
}
return max;
}
這樣的代碼,一方面性能不夠友好,另外一方面也不夠簡(jiǎn)潔,一個(gè)方法中如果全是這樣的代碼,看起來(lái)也不夠友好。但是stream誕生之后,最大值的獲取就簡(jiǎn)單太多了:
private static User maxAgeUser2(List<User> userList) {
return userList.stream().max(Comparator.comparing(User::getAge)).get();
}
整數(shù)
private static int maxInt2(List<Integer> integerList) {
return integerList.stream().max(Integer :: max).get();
}
從原來(lái)的五六行,變成了現(xiàn)在的一行,代碼更簡(jiǎn)潔,效率還更高了,豈不是美滋滋!
獲取最小值
和最大值的獲取類似,修改一下方法名就ok,這也太簡(jiǎn)單了吧:
private static User minAgeUser2(List<User> userList) {
return userList.stream().min(Comparator.comparing(User::getAge)).get();
}
整數(shù)
private static int minInt2(List<Integer> integerList) {
return integerList.stream().min(Integer :: min).get();
}
是不是很簡(jiǎn)潔,平時(shí)你寫代碼的時(shí)候也這樣寫的話,那效率豈不是剛剛的,原來(lái)要一個(gè)禮拜干完的活,現(xiàn)在只要三天,再也不用加班了……
- END -評(píng)論
圖片
表情
