java8用流收集数据

用流收集数据

汇总
long howManyDishes = menu.stream().collect(Collectors.counting());

int totalCalories = menu.stream().collect(summingInt(Dish::getCalories));
//求平均值
double avgCalories = menu.stream().collect(averagingInt(Dish::getCalories));
//summarizing操作可以得到总和.平均值.最大值.最小值
IntSummaryStatistics menuStatistics = menu.stream().collect(summarizingInt(Dish::getCalories));
//打印可得
IntSummaryStatistics{count= 9,sum=4300,min=120,average=477.777,max = 800};
查找最大值和最小值
Comparator<Dish> dishCaloriesComparator = Comparator.comparingInt(Dish::getCalories);
Optional<Dish> mostCalorieDish = menu.stream().collect(maxBy(dishCaloriesComparator));
连接字符串
//joining在内部使用了StringBuilder来把生成的字符串逐个追加起来
String shortMenu = menu.stream().map(Dish::getName).collect(joning());
//用逗号分隔
String shortMenu2 = menu.stream().map(Dish::getName).collect(joning(","));
广义的归约汇总
int totalCalories = menu.stream().collect(reducing(0,Dish::getCalories,(i,j)->j+i));

reducing需要说那个参数:

1.起始值

2.被操作的值

3.是一个BinaryOperator,将两个项目累计成一个同类型的值

同理,可以求最高热量的菜

Optional<Dish> mostCalorieDish = menu.stream().collect(reducing(d1,d2)->d1.getCalories()>d2.getCalories()?d1:d2));
分组
Map<Dish.Type,List<Dish> dishesByType = menu.stream().collect(groupingBy(Dish::getType));

复杂的分组

public enum CaloricLevel{DIET,NORMAL,FAT}

Map<CaloricLevel,List<Dish>> dishesByCaloricLevel = menu.stream().collect(
    groupingBy(dish ->{
        if(dish.getCalories()<=400) return CaloricLevel.DIET;
        else if(dish.getCalories() <= 700) return CaloricLevel.NORMAL:
        else return  CaloricLevel.FAT;
    })
);
按子组收集数据
Map<Dish.Type,Long> typesCount = menu.stream().collect(
    groupingBy(Dish::getType,counting()));

1.查找每个子组中热量最高的Dish

Map<Dish.Type,Dish> mostCaloricByType = menu.stream().collect(groupingBy(Dish::getType,collectingAndThen(
    maxBy(comparingInt(Dish::getCalories)),Optional::get)));

2.对每组进行求和

Map<Dish.Type,Integer> totalCaloriesByType = menu.stream().collect(groupingBy(Dish::getType,summingInt(Dish::getCalories)));

3.groupingBy和mapping收集器结合起来

Map<Dish.Type,Set<CaloricLevel>> caloricLevelsByType = menu.stream().collect(
    groupingBy(Dish::getType,mapping(
        dish -> {
            if(dish.getCalories()<=400) return CaloricLevel.DIET;
            else if (dish.getCalories <= 700) return CaloricLevel.NORMAL;
            else return CaloricLevel.FAT,toSet()
        }
    ))
);

分区:

Map<Boolean , List<Dish>> partitionedMenu = menu.stream().collect(partitioningBy(Dish::isVegetarian));

partitioningBy工厂方法有一个重载版本,可以传递第二收集器

Map<Boolean,Map<Dish.Type,List<Dish>>> vegetarianDishesByType = menu.stream().collect(
    partitioningBy(Dish::isVegetarian,groupingBy(Dish::getType)));

还可以重用前面的代码来找到素食和非素食中热量最高的菜:

Map<Boolean, Dish> mostVegetarian = menu.stream().collect(
    menu.stream().collect(
        partitioningBy(Dish::isVegetarian,
                      collectingAndThe(
                            maxBy(comparingInt(Dish::getCalories)),
                            Optional::get))));
将数字按质数和非质数分区
public boolean isPrime(int candidate){
    return IntStream.range(2,candidate)//产生一个自然数范围,从2开始,直至但不包括待测数
                .noneMatch(i -> candidate % i ==0);//如果待测数字不能被流中任何数字整除则返回true
}

//一个简单的优化是仅测试小于等于待测数平方根因子
public boolean isPrime(int candidate) {
  int candidateRoot = (int) Math.sqrt(candidate);
  return IntStream.rangeClosed(2, candidate).noneMatch(i -> candidate % i == 0);
}

public Map<Boolean, List<Integer>> partitionPrimes(int n) {
  return IntStream.rangeClosed(2, n).boxed().collect(partitioningBy(candidate ->                isPrime(candidate)));
}

Collectors类的静态工厂方法

工厂方法 返回类型 用于
toList List< T > 把流中所有项目收集到一个List
List< Dish > dishes = menuStream.collect(toList());
toSset Set< T > 把流中所有项目收集到一个Set,删除重复项
Set< Dish > dishes = menuStream.collect(toSet());
toCollection Collection< T > 把流中所有项目收集到给定的供应源创建的集合
Collection< Dish > dishes = menuStream.collect(toCollection(),ArrayList::new);
counting Long 计算流中元素的个数
long howManyDishes = menuStream.collect(counting());
summingInt Integer 对流中项目的一个整数属性求和
int totalCalories = menuStream.collect(summingInt(Dish::getCalories));
averagingInt Double 计算流中项目Integer属性的平均值
double avgCalories = menuStream.collect(averagingInt(Dish::getCalories));
summarizingInt IntSummaryStatistics 收集关于流中项目Integer属性的统计值,例如最大,最小,总和与平均值
IntSummaryStatistics menuStaticstics = menuStream.collect(summarizingInt(Dish::getCalories));
joining String 连接对流中每个项目调用toString方法生成的字符串
String shortMenu = menuStream.map(Dish::getName).collect(joining(", "));
maxBy Optional< T > 选出最大元素的Optional
Optional< Dish > fattest = menuStream.collect(maxBy(comparingInt(Dish::getCalories)));
minBy Optional< T > 最小元素
Optional< Dish > fattest = menuStream.collect(minBy(comparingInt(Dish::getCalories)));
reducing 归约操作产生的类型 利用BinaryOperator与流中的元素逐个结合,从而将流归约为单个值
int totalCalories = menuStream.collect(reducing(0,Dish::getCalories,Integer::sum));
collectingAndThen 转换函数返回的类型 包裹另一个收集器,对其结果应用转换函数
int howManyDishes = menuStream.collect(collectingAndThe(toList(),List::size));
groupingBy Map< K ,List< T > > 根据项目的一个属性的值对流中的项目作问组,并将属性值作为结果Map的键
Map< Dish.Type,List< Dish>> dishesByType = menuStream.collect(groupingBy(Dish::getType));
partitioningBy Map< Boolean,List< T>> 分区
Map< Boolean, List< t>> vegetarianDishes = menuStream.collect(partitioningBy(Dish::isVegetarian));

推荐阅读更多精彩内容