您好,登錄后才能下訂單哦!
小編給大家分享一下Java8處理List中雙層循環(huán)問(wèn)題的解決方法,希望大家閱讀完這篇文章后大所收獲,下面讓我們一起去探討吧!
Java處理List的雙層循環(huán)程序員經(jīng)常遇到,一般都是當(dāng)兩個(gè)List某個(gè)值滿(mǎn)足某條件時(shí)候,進(jìn)行相應(yīng)的處理;
1.list和map之間的相互轉(zhuǎn)換
/** * 兩個(gè)List對(duì)象當(dāng)id相同的時(shí)候(注意是兩個(gè)對(duì)象,而非兩個(gè)集合) * @param husbands * @param wives */ private static void test8(List<Husband> husbands, List<Wife> wives) { List<Family> families = Lists.newArrayList(); //將wives轉(zhuǎn)換為map,這里的key一定要唯一,即為familyId Map<Integer, Wife> wifeMap = wives.stream().collect(toMap(w -> w.getFamilyId(), w -> w)); families = husbands.stream().map(husband -> { Family family = new Family(); Wife wife = wifeMap.get(husband.getFamilyId()); family.setFamilyId(wife.getFamilyId()); family.setHusbandName(husband.getHusbandName()); family.setWifeName(husband.getWifename()); return family; }).collect(Collectors.toList()); }
2.java8中的
groupingBy
counting
mapToDouble
filter
sum等函數(shù)方法的使用
//蘋(píng)果顏色對(duì)應(yīng)的數(shù)量 Map<String, Long> collect = appleVos.stream().collect(groupingBy(AppleVo::getColor, counting())); // 過(guò)濾掉顏色為黑色的蘋(píng)果,并匯總好蘋(píng)果的總金額 Double sum = appleVos.stream().filter(i -> "black".equals(i.getColor())).mapToDouble(AppleVo::getPrice).sum();
補(bǔ)充知識(shí):java8新技術(shù):數(shù)據(jù)流式處理之兩個(gè)list集合多對(duì)多遍歷關(guān)聯(lián)
自用測(cè)試方法
說(shuō)明一下:list1和list2兩個(gè)集合進(jìn)行匹配,將list2中的對(duì)應(yīng)的值取出,使list1中的每條數(shù)據(jù)都有對(duì)應(yīng)的list2中的name值,list1為主集合,數(shù)據(jù)需全部展示;
注意:若list1的數(shù)量多于list2,并且數(shù)據(jù)匹配不上,則多出來(lái)的會(huì)在list3中為null;
看完了這篇文章,相信你對(duì)Java8處理List中雙層循環(huán)問(wèn)題的解決方法有了一定的了解,想了解更多相關(guān)知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。