原创转载请注明出处:http://agilestyle.iteye.com/blog/2425965
Outline
testPartitioningByWithPredicate();
testPartitionByWithPredicateAndCollector();
testReducingBinaryOperator();
testReducingBinaryOperatorAndIdentity();
testReducingBinaryOperatorAndIdentityAndFunction();
testSummarizingInt();
testSummarizingLong();
testSummarizingDouble();
SRC
package org.fool.java8.collector; import java.util.Arrays; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.function.BinaryOperator; import java.util.stream.Collectors; public class CollectorsTest3 { private static List<Dish> menu = Arrays.asList( new Dish("pork", false, 800, Dish.Type.MEAT), new Dish("beef", false, 700, Dish.Type.MEAT), new Dish("chicken", false, 400, Dish.Type.MEAT), new Dish("french fries", true, 530, Dish.Type.OTHER), new Dish("rice", true, 350, Dish.Type.OTHER), new Dish("season fruit", true, 120, Dish.Type.OTHER), new Dish("pizza", true, 550, Dish.Type.OTHER), new Dish("prawns", false, 300, Dish.Type.FISH), new Dish("salmon", false, 450, Dish.Type.FISH) ); public static void main(String[] args) { testPartitioningByWithPredicate(); testPartitionByWithPredicateAndCollector(); testReducingBinaryOperator(); testReducingBinaryOperatorAndIdentity(); testReducingBinaryOperatorAndIdentityAndFunction(); testSummarizingInt(); testSummarizingLong(); testSummarizingDouble(); } private static void testPartitioningByWithPredicate() { Map<Boolean, List<Dish>> collect = menu.stream().collect(Collectors.partitioningBy(Dish::isVegetarian)); Optional.of(collect).ifPresent(System.out::println); } private static void testPartitionByWithPredicateAndCollector() { Map<Boolean, Double> collect = menu.stream().collect(Collectors.partitioningBy(Dish::isVegetarian, Collectors.averagingInt(Dish::getCalories))); Optional.of(collect).ifPresent(System.out::println); } private static void testReducingBinaryOperator() { menu.stream().collect(Collectors.reducing(BinaryOperator.maxBy(Comparator.comparingInt(Dish::getCalories)))) .ifPresent(System.out::println); } private static void testReducingBinaryOperatorAndIdentity() { Integer collect = menu.stream().map(Dish::getCalories).collect(Collectors.reducing(0, (d1, d2) -> d1 + d2)); System.out.println(collect); } private static void testReducingBinaryOperatorAndIdentityAndFunction() { Integer collect = menu.stream().collect(Collectors.reducing(0, Dish::getCalories, (d1, d2) -> d1 + d2)); System.out.println(collect); } private static void testSummarizingInt() { Optional.of(menu.stream().collect(Collectors.summarizingInt(Dish::getCalories))).ifPresent(System.out::println); } private static void testSummarizingLong() { Optional.of(menu.stream().collect(Collectors.summarizingLong(Dish::getCalories))).ifPresent(System.out::println); } private static void testSummarizingDouble() { Optional.of(menu.stream().collect(Collectors.summarizingDouble(Dish::getCalories))).ifPresent(System.out::println); } public static class Dish { private String name; private boolean vegetarian; private int calories; private Type type; public Dish(String name, boolean vegetarian, int calories, Type type) { this.name = name; this.vegetarian = vegetarian; this.calories = calories; this.type = type; } public enum Type { MEAT, FISH, OTHER } public String getName() { return name; } public void setName(String name) { this.name = name; } public boolean isVegetarian() { return vegetarian; } public void setVegetarian(boolean vegetarian) { this.vegetarian = vegetarian; } public int getCalories() { return calories; } public void setCalories(int calories) { this.calories = calories; } public Type getType() { return type; } public void setType(Type type) { this.type = type; } @Override public String toString() { return "Dish{" + "name='" + name + '\'' + ", vegetarian=" + vegetarian + ", calories=" + calories + ", type=" + type + '}'; } } }
Console Output
{false=[Dish{name='pork', vegetarian=false, calories=800, type=MEAT}, Dish{name='beef', vegetarian=false, calories=700, type=MEAT}, Dish{name='chicken', vegetarian=false, calories=400, type=MEAT}, Dish{name='prawns', vegetarian=false, calories=300, type=FISH}, Dish{name='salmon', vegetarian=false, calories=450, type=FISH}], true=[Dish{name='french fries', vegetarian=true, calories=530, type=OTHER}, Dish{name='rice', vegetarian=true, calories=350, type=OTHER}, Dish{name='season fruit', vegetarian=true, calories=120, type=OTHER}, Dish{name='pizza', vegetarian=true, calories=550, type=OTHER}]} {false=530.0, true=387.5} Dish{name='pork', vegetarian=false, calories=800, type=MEAT} 4200 4200 IntSummaryStatistics{count=9, sum=4200, min=120, average=466.666667, max=800} LongSummaryStatistics{count=9, sum=4200, min=120, average=466.666667, max=800} DoubleSummaryStatistics{count=9, sum=4200.000000, min=120.000000, average=466.666667, max=800.000000}
相关推荐
java stream源码预定义的Java流收集器 介绍 有几种方法可以将Stream作为一系列输入元素....hasSize(3) .containsOnly(1, 2, 3); 要收集要设置的Stream,可以使用toSet方法中的收集器。 不能保证返回的Set的类型,可变性
3. **Stream API**:Stream API提供了一种处理集合数据的新方式,它支持串行和并行操作。通过stream,可以进行过滤、映射、分组、聚合等操作。例如,`filter()`方法用于筛选元素,`map()`方法用于转换元素,`collect...
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6); List<Integer> evenNumbers = numbers.stream() .filter(n -> n % 2 == 0) .collect(Collectors.toList()); ``` 此外,`java.util.function`包下的...
.collect(Collectors.toList()); ``` 4. **方法引用** 方法引用是lambda表达式的补充,它可以直接引用已有方法,而无需重新定义。例如,我们可以用`String::length`代替lambda `(s) -> s.length()`: ```java ...
List<String> list = Stream.of("a", "b", "c").map(String::new).collect(Collectors.toList()); ``` 四、Stream API Java 8引入了Stream API,它提供了一种新的数据处理方式,类似于SQL查询,可以对集合进行过滤...
本文将围绕"Hj212-master_hj212解析器_hj212-master_hj-212java_212_212协议解析demo"这一主题,深入探讨HJ212协议的解析原理,以及如何利用Java实现解析器,并通过示例演示其实现过程。 首先,理解HJ212协议的基础...
my kids who are stamp collectors. Do not use an envelop, I collect USED postcards sent to me. Write on the postcard that it is your ICS registration. Address your card to: Francois PIETTE, rue de ...
3. **@PathVariable**:用于从URL路径中提取动态值。例如,`@GetMapping("/users/{id}")`,其中{id}就是路径变量,可以通过@PathVariable("id")获取其值。 4. **@RequestParam**:用于从HTTP请求参数中获取值。例如...
.collect(Collectors.toList()); ``` 这段代码展示了如何使用Stream API从列表中筛选出所有偶数。 **3. 泛型** 泛型是一种编写可重用代码的技术,它允许在编译时检查类型安全,并且所有的强制转换都是自动和隐式...
3. 自定义循环:最基础的方法是通过循环遍历ArrayList,每次添加新元素前检查它是否已存在。如果不存在,则添加到新的ArrayList中: ```java ArrayList<String> uniqueList = new ArrayList(); for (String item : ...
JDK8 Collectors.toMap IllegalStateException Duplicate key DEMO
在这个"用HashMap写的一个小Demo用来写游戏排名的一种方法"的示例中,我们很可能会看到如何利用HashMap来组织游戏分数并进行排序,以实现一个简单的游戏排名系统。 HashMap的特点在于它的键(key)是唯一的,每个键...
List<String> squares = numbers.stream().map(n -> n * n).mapToObj(Integer::toString).collect(Collectors.toList()); ``` 3. **收集(Collect)**:将Stream结果转换回集合或其他形式。 ```java Set...
.collect(Collectors.toList()); ``` 这里,`map()`函数接受一个`Demo`对象,然后通过构造函数`new KeyValueVo(result.getKey(), result.getValue())`创建一个新的`KeyValueVo`对象。`collect()`方法将所有转换后的...
3. **Java 8的Optional类** Java 8引入了Optional类,它是一个容器类,代表一个值存在或不存在。这提供了一种更安全的方式来处理可能为NULL的对象,避免了NullPointerException。使用Optional可以这样写: ```java...
3. **单词统计**: 在词频统计中,首先需要读取文本文件,然后将文本内容转换为单词的Stream。这可能通过`Files.lines()`方法读取文件,然后使用`map()`将每一行拆分为单词。接着,使用`filter()`去除标点符号和非...
例如,你可以看到如何使用`filter()`筛选出满足特定条件的元素,`map()`将元素转换为另一种类型,`reduce()`用于累加或聚合操作,以及`collect()`配合`Collectors`工具类实现分组、收集到特定集合等复杂操作。...
分布式跟踪系统是现代微服务架构中的重要组成部分,它帮助...这个压缩包中的"demo"可能是示例代码或者一个简单的微服务应用,可以作为实践Zipkin和Spring Boot集成的起点,帮助我们深入理解分布式跟踪系统的工作原理。
在Java 8的Stream API中,Lambda表达式常用于过滤、映射和聚合等操作,如 `list.stream().filter(s -> s.startsWith("A")).map(String::toUpperCase).collect(Collectors.toList());`。 标签“Lambda学习”表明教程...
List<String> strings = Lists.newArrayList(1, 2, 3); List<String> stringList = Collections2.transform(strings, new Function, String>() { @Override public String apply(Integer input) { return input....