原创转载请注明出处:http://agilestyle.iteye.com/blog/2425963
Outline
testAveragingDouble();
testAveragingInt();
testAveragingLong();
testCollectingAndThen1();
testCollectingAndThen2();
testCounting();
testGroupingByFunction1();
testGroupingByFunction2();
testGroupingByFunction3();
testSummarizingInt();
SRC
package org.fool.java8.collector; import java.util.Arrays; import java.util.Collections; import java.util.IntSummaryStatistics; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.TreeMap; import java.util.stream.Collectors; public class CollectorsTest { 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) { testAveragingDouble(); testAveragingInt(); testAveragingLong(); testCollectingAndThen1(); testCollectingAndThen2(); testCounting(); testGroupingByFunction1(); testGroupingByFunction2(); testGroupingByFunction3(); testSummarizingInt(); } private static void testAveragingDouble() { Optional.ofNullable(menu.stream().collect(Collectors.averagingDouble(Dish::getCalories))).ifPresent(System.out::println); } private static void testAveragingInt() { Optional.ofNullable(menu.stream().collect(Collectors.averagingInt(Dish::getCalories))).ifPresent(System.out::println); } private static void testAveragingLong() { Optional.ofNullable(menu.stream().collect(Collectors.averagingLong(Dish::getCalories))).ifPresent(System.out::println); } private static void testCollectingAndThen1() { Optional.ofNullable(menu.stream(). collect(Collectors.collectingAndThen(Collectors.averagingInt(Dish::getCalories), a -> "The average calories is " + a))). ifPresent(System.out::println); } private static void testCollectingAndThen2() { List<Dish> result = menu.stream(). filter(d -> d.getType().equals(Dish.Type.MEAT)). collect(Collectors.collectingAndThen(Collectors.toList(), Collections::unmodifiableList)); //result.add(new Dish("", false, 100, Dish.Type.OTHER)); System.out.println(result); } private static void testCounting() { Optional.of(menu.stream().collect(Collectors.counting())).ifPresent(System.out::println); } private static void testGroupingByFunction1() { Optional.ofNullable(menu.stream().collect(Collectors.groupingBy(Dish::getType))).ifPresent(System.out::println); } private static void testGroupingByFunction2() { Optional.ofNullable(menu.stream(). collect(Collectors.groupingBy(Dish::getType, Collectors.counting()))). ifPresent(System.out::println); } private static void testGroupingByFunction3() { Map<Dish.Type, Double> map = menu.stream(). collect(Collectors.groupingBy(Dish::getType, TreeMap::new, Collectors.averagingInt(Dish::getCalories))); Optional.of(map.getClass()).ifPresent(System.out::println); Optional.of(map).ifPresent(System.out::println); } private static void testSummarizingInt() { IntSummaryStatistics result = menu.stream().collect(Collectors.summarizingInt(Dish::getCalories)); Optional.of(result).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
466.6666666666667 466.6666666666667 466.6666666666667 The average calories is 466.6666666666667 [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}] 9 {OTHER=[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}], FISH=[Dish{name='prawns', vegetarian=false, calories=300, type=FISH}, Dish{name='salmon', vegetarian=false, calories=450, type=FISH}], MEAT=[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}]} {OTHER=4, FISH=2, MEAT=3} class java.util.TreeMap {MEAT=633.3333333333334, FISH=375.0, OTHER=387.5} IntSummaryStatistics{count=9, sum=4200, min=120, average=466.666667, max=800}
相关推荐
java stream源码预定义的Java流收集器 ...2, 3) .collect(toList()); assertThat(list) .hasSize(3) .containsOnly(1, 2, 3); 要收集要设置的Stream,可以使用toSet方法中的收集器。 不能保证返回的Set的类型,可变性
2. **函数式接口**:为了支持lambda,Java 8定义了一组内置的函数式接口,如Runnable、Callable、Consumer、Supplier、Predicate、Function等。这些接口有一个抽象方法,因此可以被lambda表达式实例化。例如,`...
.collect(Collectors.toList()); ``` 此外,`java.util.function`包下的接口如Predicate(断言)、Function(函数)和Consumer(消费)等,都是Lambda表达式常用的接口。这些接口可以配合Lambda表达式进行函数式...
.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 ...
return phoneNumbers.stream().collect(Collectors.toMap(phone -> phone, phone -> true)); } } ``` 在这个例子中,`/sms/send`接口使用GET方法接收一个电话号码参数,而`/sms/bulkSend`接口使用POST方法接收一...
.collect(Collectors.toList()); ``` 这段代码展示了如何使用Stream API从列表中筛选出所有偶数。 **3. 泛型** 泛型是一种编写可重用代码的技术,它允许在编译时检查类型安全,并且所有的强制转换都是自动和隐式...
2. 使用流(Stream) API:Java 8引入了流API,它提供了非常方便的处理集合的方式。我们可以使用distinct()方法来获取唯一元素: ```java list = list.stream() .distinct() .collect(Collectors.toList()); ``` 3...
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...
2. **基本的NULL检查** 最基础的NULL检查方式是使用`if`语句。例如: ```java if (object != null) { object.doSomething(); } ``` 这种方式可以避免在对象为NULL时执行方法,但代码可读性较差,尤其是当有...
.collect(Collectors.toList()); ``` 这里,`map()`函数接受一个`Demo`对象,然后通过构造函数`new KeyValueVo(result.getKey(), result.getValue())`创建一个新的`KeyValueVo`对象。`collect()`方法将所有转换后的...
2. **Stream操作流程**: - **中间操作(Intermediate Operations)**:例如`filter()`和`map()`,它们不会立即执行,而是构建一个操作链。这些操作会返回一个新的Stream,可以在链上继续添加其他操作。 - **终止...
例如,你可以看到如何使用`filter()`筛选出满足特定条件的元素,`map()`将元素转换为另一种类型,`reduce()`用于累加或聚合操作,以及`collect()`配合`Collectors`工具类实现分组、收集到特定集合等复杂操作。...
2. **Collectors**:收集来自各个服务的追踪数据。在Spring Boot应用中,通常使用Zipkin的Brave库来集成收集器。 3. **Storage**:存储收集到的追踪数据,常见的存储后端有MySQL、Cassandra和Elasticsearch等。 4....
在Java 8的Stream API中,Lambda表达式常用于过滤、映射和聚合等操作,如 `list.stream().filter(s -> s.startsWith("A")).map(String::toUpperCase).collect(Collectors.toList());`。 标签“Lambda学习”表明教程...
.collect(Collectors.toList()); ``` 接下来,我们转向Guava的EventBus。EventBus是一种观察者模式的实现,它允许组件之间通过发布和订阅事件进行通信,而不必显式地相互依赖。通过注册到EventBus的订阅者可以接收...