寫Java接口的朋友都知道,Java 8的更新,經(jīng)常會(huì)用到過濾 list<Object> 里的數(shù)據(jù),本文就對(duì)List使用Stream流進(jìn)行集合Collection的各種運(yùn)算做一個(gè)匯總! 優(yōu)勢(shì):Stream 是對(duì)集合(Collection)對(duì)象功能的增強(qiáng),它專注于對(duì)集合對(duì)象進(jìn)行各種非常便利、高效的聚合操作,或者大批量數(shù)據(jù)操作。 通常我們需要多行代碼才能完成的操作,借助于Stream流式處理可以很簡(jiǎn)單的實(shí)現(xiàn)。 各種Stream流操作:
List<Object> soList = Lists.newArrayList(); List<Object> list = soList.stream().filter(item -> item.getName() != null).collect(Collectors.toList());
List<Object> soList = Lists.newArrayList() //distinct() 去重 List<Integer> maxDueDayList2 = soList.stream().map(Object::getMaxDueDay).distinct().collect(Collectors.toList());
int total = list.stream().mapToInt(User::getAge).sum(); //上下等同 int ageSum = userList.stream().collect(Collectors.summingInt(User::getAge));
double doublesum = listUsers.stream().mapToDouble(Users::getAge).sum();//和 int intmax = listUsers.stream().mapToInt(Users::getAge).max().getAsInt();//最大 int intmin = listUsers.stream().mapToInt(Users::getAge).min().getAsInt();//最小 double avg = listUsers.stream().mapToDouble(Users::getAge).average().getAsDouble();//平均 //計(jì)算一個(gè)number類型的List對(duì)象 Integer[] integerArray = {1, 3, 5, 10, 18}; List<Integer> list = new ArrayList<>(Arrays.asList(integerArray)); IntSummaryStatistics summaryStatistics = list.stream().mapToInt((s) -> s).summaryStatistics(); System.out.println("總和:" + summaryStatistics.getSum()); System.out.println("平均數(shù):" + summaryStatistics.getAverage()); System.out.println("總個(gè)數(shù):" + summaryStatistics.getCount()); System.out.println("最大值:" + summaryStatistics.getMax()); System.out.println("最小值:" + summaryStatistics.getMin());
Collections.sort(list, (o1, o2) -> o1.getCustomerCount() - o2.getCustomerCount()); List<Integer> ss = new ArrayList<>(); Collections.sort(ss, (o1, o2) -> (o1 - o2));
List<String> stIdList1 = stuList.stream().map(Student::getId).collect(Collectors.toList());
BigDecimal result = fileDatas.stream() // 將user對(duì)象的age取出來(lái)map為Bigdecimal .map(IpayRepayFileData::getTotalAmount) // 使用reduce()聚合函數(shù),實(shí)現(xiàn)累加器 .reduce(BigDecimal.ZERO,BigDecimal::add); reduce是一個(gè)終結(jié)操作,它能夠通過某一個(gè)方法,對(duì)元素進(jìn)行削減操作。該操作的結(jié)果會(huì)放在一個(gè)Optional變量里返回。可以利用它來(lái)實(shí)現(xiàn)很多聚合方法比如count,max,min等。 T reduce(T identity, BinaryOperator accumulator);
大家如果還有其他list的操作歡迎評(píng)論補(bǔ)充! |
|