原创转载请注明出处:http://agilestyle.iteye.com/blog/2425964
Outline
testGroupingByConcurrent();
testGroupingByConcurrentWithFunctionAndCollector();
testGroupingByConcurrentWithFunctionAndSupplierAndCollector();
testJoining();
testJoiningWithDelimiter();
testJoiningWithDelimiterAndPrefixAndSuffix();
testMapping();
testMaxBy();
testMinBy();
SRC
package org.fool.java8.collector; import java.util.Arrays; import java.util.Comparator; import java.util.List; import java.util.Optional; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ConcurrentSkipListMap; import java.util.stream.Collectors; public class CollectorsTest2 { 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) { testGroupingByConcurrent(); testGroupingByConcurrentWithFunctionAndCollector(); testGroupingByConcurrentWithFunctionAndSupplierAndCollector(); testJoining(); testJoiningWithDelimiter(); testJoiningWithDelimiterAndPrefixAndSuffix(); testMapping(); testMaxBy(); testMinBy(); } private static void testGroupingByConcurrent() { ConcurrentMap<Dish.Type, List<Dish>> map = menu.stream().collect(Collectors.groupingByConcurrent(Dish::getType)); Optional.ofNullable(map.getClass()).ifPresent(System.out::println); Optional.ofNullable(map).ifPresent(System.out::println); } private static void testGroupingByConcurrentWithFunctionAndCollector() { ConcurrentMap<Dish.Type, Double> map = menu.stream().collect(Collectors.groupingByConcurrent(Dish::getType, Collectors.averagingInt(Dish::getCalories))); Optional.ofNullable(map).ifPresent(System.out::println); } private static void testGroupingByConcurrentWithFunctionAndSupplierAndCollector() { ConcurrentMap<Dish.Type, Double> map = menu.stream() .collect(Collectors.groupingByConcurrent(Dish::getType, ConcurrentSkipListMap::new, Collectors.averagingInt(Dish::getCalories))); Optional.ofNullable(map.getClass()).ifPresent(System.out::println); Optional.ofNullable(map).ifPresent(System.out::println); } private static void testJoining() { Optional.ofNullable(menu.stream().map(Dish::getName).collect(Collectors.joining())).ifPresent(System.out::println); } private static void testJoiningWithDelimiter() { Optional.ofNullable(menu.stream().map(Dish::getName).collect(Collectors.joining(","))).ifPresent(System.out::println); } private static void testJoiningWithDelimiterAndPrefixAndSuffix() { Optional.ofNullable(menu.stream().map(Dish::getName).collect(Collectors.joining(",", "Name[", "]"))).ifPresent(System.out::println); } private static void testMapping() { Optional.ofNullable(menu.stream().collect(Collectors.mapping(Dish::getName, Collectors.joining(",")))).ifPresent(System.out::println); Optional.ofNullable(menu.stream().map(Dish::getName).collect(Collectors.joining(","))).ifPresent(System.out::println); } private static void testMaxBy() { Optional.ofNullable(menu.stream().collect(Collectors.maxBy(Comparator.comparingInt(Dish::getCalories)))).ifPresent(System.out::println); Optional.ofNullable(menu.stream().max(Comparator.comparingInt(Dish::getCalories))).ifPresent(System.out::println); } private static void testMinBy() { Optional.ofNullable(menu.stream().collect(Collectors.minBy(Comparator.comparingInt(Dish::getCalories)))).ifPresent(System.out::println); Optional.ofNullable(menu.stream().min(Comparator.comparingInt(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
class java.util.concurrent.ConcurrentHashMap {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}], 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}], FISH=[Dish{name='prawns', vegetarian=false, calories=300, type=FISH}, Dish{name='salmon', vegetarian=false, calories=450, type=FISH}]} {OTHER=387.5, MEAT=633.3333333333334, FISH=375.0} class java.util.concurrent.ConcurrentSkipListMap {MEAT=633.3333333333334, FISH=375.0, OTHER=387.5} porkbeefchickenfrench friesriceseason fruitpizzaprawnssalmon pork,beef,chicken,french fries,rice,season fruit,pizza,prawns,salmon Name[pork,beef,chicken,french fries,rice,season fruit,pizza,prawns,salmon] pork,beef,chicken,french fries,rice,season fruit,pizza,prawns,salmon pork,beef,chicken,french fries,rice,season fruit,pizza,prawns,salmon Optional[Dish{name='pork', vegetarian=false, calories=800, type=MEAT}] Optional[Dish{name='pork', vegetarian=false, calories=800, type=MEAT}] Optional[Dish{name='season fruit', vegetarian=true, calories=120, type=OTHER}] Optional[Dish{name='season fruit', vegetarian=true, calories=120, type=OTHER}]
相关推荐
java ...Stream.of(1, 2, 3) .collect(toList()); assertThat(list) .hasSize(3) .containsOnly(1, 2, 3); 要收集要设置的Stream,可以使用toSet方法中的收集器。 不能保证返回的Set的类型,可变性
1. **lambda表达式**:Java 8引入了函数式编程的概念,其中lambda表达式是最显著的特征。Lambda允许我们将函数作为方法参数,或者作为一个新的数据类型。通过lambda,可以更简洁地表示那些只需要一次使用的匿名函数...
.collect(Collectors.toList()); ``` 4. **方法引用** 方法引用是lambda表达式的补充,它可以直接引用已有方法,而无需重新定义。例如,我们可以用`String::length`代替lambda `(s) -> s.length()`: ```java ...
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`包下的...
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. 泛型** 泛型是一种编写可重用代码的技术,它允许在编译时检查类型安全,并且所有的强制转换都是自动和隐式...
1. 使用HashSet:HashSet是Java中的一个无序、不重复元素的集合。当我们尝试将一个元素添加到HashSet时,如果该元素已经存在,它将被忽略,因此可以轻松地去除重复。以下是一个简单的示例: ```java ArrayList...
在这个"用HashMap写的一个小Demo用来写游戏排名的一种方法"的示例中,我们很可能会看到如何利用HashMap来组织游戏分数并进行排序,以实现一个简单的游戏排名系统。 HashMap的特点在于它的键(key)是唯一的,每个键...
JDK8 Collectors.toMap IllegalStateException Duplicate key DEMO
List<String> squares = numbers.stream().map(n -> n * n).mapToObj(Integer::toString).collect(Collectors.toList()); ``` 3. **收集(Collect)**:将Stream结果转换回集合或其他形式。 ```java Set...
1. **NullPointerException的理解** NullPointerException是Java中的一个运行时异常,当程序试图在需要对象的地方使用NULL时抛出。例如,当你尝试调用一个NULL对象的方法或访问其字段时,就会抛出此异常。 2. **...
.collect(Collectors.toList()); ``` 这里,`map()`函数接受一个`Demo`对象,然后通过构造函数`new KeyValueVo(result.getKey(), result.getValue())`创建一个新的`KeyValueVo`对象。`collect()`方法将所有转换后的...
根据提供的文件名称列表,我们有`java答辩`和`demo1`两个文件。`java答辩`可能是一个包含PPT的文件,用于展示和解释项目;而`demo1`可能是源代码或者测试数据。 总之,这个“java大作业之词频统计”项目展示了如何...
System.out.println(max.orElse(-1)); ``` 这个例子中,`stream()`用于创建流,`max()`是终端操作,`Integer::compareTo`是方法引用,相当于 `(a, b) -> a.compareTo(b)`。 总的来说,“Java8 流式Lambda相关案例...
1. **Zipkin Server**:这是整个系统的中心,负责接收来自各个服务的追踪数据,并提供Web界面供用户查询和分析。 2. **Collectors**:收集来自各个服务的追踪数据。在Spring Boot应用中,通常使用Zipkin的Brave库来...
在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....