原创转载请注明出处:http://agilestyle.iteye.com/blog/2425966
Outline
testSummingDouble();
testSummingLong();
testSummingInt();
testToCollection();
testToConcurrentMap();
testToConcurrentMapWithBinaryOperator();
testToConcurrentMapWithBinaryOperatorAndSupplier();
testToList();
testToSet();
testToMap();
testToMapWithBinaryOperator();
testToMapWithBinaryOperatorAndSupplier();
SRC
package org.fool.java8.collector; import java.util.Arrays; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Optional; import java.util.concurrent.ConcurrentSkipListMap; import java.util.stream.Collectors; public class CollectorsTest4 { 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) { testSummingDouble(); testSummingLong(); testSummingInt(); testToCollection(); testToConcurrentMap(); testToConcurrentMapWithBinaryOperator(); testToConcurrentMapWithBinaryOperatorAndSupplier(); testToList(); testToSet(); testToMap(); testToMapWithBinaryOperator(); testToMapWithBinaryOperatorAndSupplier(); } private static void testSummingDouble() { Optional.of(menu.stream().collect(Collectors.summingDouble(Dish::getCalories))).ifPresent(System.out::println); Optional.of(menu.stream().mapToDouble(Dish::getCalories).sum()).ifPresent(System.out::println); } private static void testSummingLong() { Optional.of(menu.stream().collect(Collectors.summingLong(Dish::getCalories))).ifPresent(System.out::println); Optional.of(menu.stream().mapToLong(Dish::getCalories).sum()).ifPresent(System.out::println); } private static void testSummingInt() { Optional.of(menu.stream().collect(Collectors.summingInt(Dish::getCalories))).ifPresent(System.out::println); Optional.of(menu.stream().mapToInt(Dish::getCalories).sum()).ifPresent(System.out::println); } private static void testToCollection() { LinkedList<Dish> collect = menu.stream().filter(d -> d.getCalories() > 600).collect(Collectors.toCollection(LinkedList::new)); Optional.of(collect).ifPresent(System.out::println); } private static void testToConcurrentMap() { Optional.of(menu.stream().collect(Collectors.toConcurrentMap(Dish::getName, Dish::getCalories))).ifPresent(System.out::println); } private static void testToConcurrentMapWithBinaryOperator() { Optional.of(menu.stream().collect(Collectors.toConcurrentMap(Dish::getType, v -> 1L, (a, b) -> a + b))).ifPresent(System.out::println); } private static void testToConcurrentMapWithBinaryOperatorAndSupplier() { Optional.of(menu.stream().collect(Collectors.toConcurrentMap(Dish::getType, v -> 1L, (a, b) -> a + b, ConcurrentSkipListMap::new))) .ifPresent(v -> { System.out.println(v); System.out.println(v.getClass()); }); } private static void testToList() { Optional.of(menu.stream().filter(Dish::isVegetarian).collect(Collectors.toList())).ifPresent( r -> { System.out.println(r.getClass()); System.out.println(r); } ); } private static void testToSet() { Optional.of(menu.stream().filter(Dish::isVegetarian).collect(Collectors.toSet())).ifPresent( r -> { System.out.println(r.getClass()); System.out.println(r); } ); } private static void testToMap() { Optional.of(menu.stream().collect(Collectors.toMap(Dish::getName, Dish::getCalories))).ifPresent(System.out::println); } private static void testToMapWithBinaryOperator() { Optional.of(menu.stream().collect(Collectors.toMap(Dish::getType, v -> 1L, (a, b) -> a + b))).ifPresent(System.out::println); } private static void testToMapWithBinaryOperatorAndSupplier() { Optional.of(menu.stream().collect(Collectors.toMap(Dish::getType, v -> 1L, (a, b) -> a + b, HashMap::new))) .ifPresent(v -> { System.out.println(v); System.out.println(v.getClass()); }); } 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
4200.0 4200.0 4200 4200 4200 4200 [Dish{name='pork', vegetarian=false, calories=800, type=MEAT}, Dish{name='beef', vegetarian=false, calories=700, type=MEAT}] {season fruit=120, chicken=400, pizza=550, salmon=450, beef=700, pork=800, rice=350, french fries=530, prawns=300} {MEAT=3, OTHER=4, FISH=2} {MEAT=3, FISH=2, OTHER=4} class java.util.concurrent.ConcurrentSkipListMap class java.util.ArrayList [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}] class java.util.HashSet [Dish{name='rice', vegetarian=true, calories=350, type=OTHER}, Dish{name='pizza', vegetarian=true, calories=550, type=OTHER}, Dish{name='season fruit', vegetarian=true, calories=120, type=OTHER}, Dish{name='french fries', vegetarian=true, calories=530, type=OTHER}] {season fruit=120, chicken=400, pizza=550, salmon=450, beef=700, rice=350, pork=800, prawns=300, french fries=530} {MEAT=3, OTHER=4, FISH=2} {MEAT=3, OTHER=4, FISH=2} class java.util.HashMap
相关推荐
java stream源码预定义的Java流收集器 介绍 有几种方法可以将Stream作为一系列输入元素简化为一个汇总结果。 其中之一是使用接口与方法的实现。 可以显式实现此接口,但是它应该从类中研究其预定义的实现开始。...
4. **方法引用**:方法引用来代替lambda表达式,当函数体与已存在的方法相同时,可以更直观地引用该方法。例如,`Arrays.sort(list, List::compareTo)`使用了`List`接口的`compareTo`方法。 5. **日期和时间API**:...
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查询,可以对集合进行过滤...
4. **数据结构化**:将解码后的数据转换为Java对象,便于后续处理和存储。 在实现HJ212解析器时,我们可能需要设计一个自定义的`HJ212Parser`类,它包括输入流读取、报文解析、数据结构化等方法。例如,`parseJson...
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. 泛型** 泛型是一种编写可重用代码的技术,它允许在编译时检查类型安全,并且所有的强制转换都是自动和隐式...
.collect(Collectors.toList()); ``` 3. 自定义循环:最基础的方法是通过循环遍历ArrayList,每次添加新元素前检查它是否已存在。如果不存在,则添加到新的ArrayList中: ```java ArrayList<String> uniqueList =...
JDK8 Collectors.toMap IllegalStateException Duplicate key DEMO
List<String> longNames = names.stream().filter(name -> name.length() > 4).collect(Collectors.toList()); ``` 2. **映射(Map)**:将每个元素转换成另一个值。 ```java List<Integer> numbers = Arrays....
在这个"用HashMap写的一个小Demo用来写游戏排名的一种方法"的示例中,我们很可能会看到如何利用HashMap来组织游戏分数并进行排序,以实现一个简单的游戏排名系统。 HashMap的特点在于它的键(key)是唯一的,每个键...
4. **Null对象模式** 在设计模式中,有一种称为Null对象模式的策略,用于在对象为NULL时提供默认行为。创建一个接口的实现,该实现不执行任何操作,而不是抛出异常,可以避免NULL检查。 5. **断言(Assertions)**...
.collect(Collectors.toList()); ``` 这里,`map()`函数接受一个`Demo`对象,然后通过构造函数`new KeyValueVo(result.getKey(), result.getValue())`创建一个新的`KeyValueVo`对象。`collect()`方法将所有转换后的...
4. **函数式编程**: Java 8的Stream API体现了函数式编程的思想,它鼓励使用无状态和无副作用的函数,使得代码更易于测试和理解。在这个项目中,我们可能会定义一些Lambda表达式来实现过滤、映射等操作。 5. **...
例如,你可以看到如何使用`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学习”表明教程...
.collect(Collectors.toList()); ``` 接下来,我们转向Guava的EventBus。EventBus是一种观察者模式的实现,它允许组件之间通过发布和订阅事件进行通信,而不必显式地相互依赖。通过注册到EventBus的订阅者可以接收...