细品Java 8 之《java8-the-missing-tutorial》
2018-02-03 17:35
274 查看
闲下来,翻看知乎上的一些关于Java 的文章,发现《不可或缺的 Java 8 开源项目》这一文章,收录了不少Java 8 资源,刚看到第二个《java8-the-missing-tutorial》就被其深深吸引,当天晚上看到10点半才舍得从公司回家,今天接着看第三章,讲的是Collectors工具类的一些用法,复杂的查询,排序,分组用干净的简单的代码就可以轻松实现,看得我激动不已,直到最后,看到这样一段代码,差点没有压抑住内心的激动兴奋之情。简直就是太棒了,太牛逼了。代码贴出来,日后能用到,如下:
import com.google.common.collect.HashMultiset; import com.google.common.collect.Multiset; import java.util.Collections; import java.util.EnumSet; import java.util.Set; import java.util.function.BiConsumer; import java.util.function.BinaryOperator; import java.util.function.Function; import java.util.function.Supplier; import java.util.stream.Collector; public class MultisetCollector<T> implements Collector<T, Multiset<T>, Multiset<T>> { @Override public Supplier<Multiset<T>> supplier() { return HashMultiset::create; } @Override public BiConsumer<Multiset<T>, T> accumulator() { return (set, e) -> set.add(e, 1); } @Override public BinaryOperator<Multiset<T>> combiner() { return (set1, set2) -> { set1.addAll(set2); return set1; }; } @Override public Function<Multiset<T>, Multiset<T>> finisher() { return Function.identity(); } @Override public Set<Characteristics> characteristics() { return Collections.unmodifiableSet(EnumSet.of(Characteristics.IDENTITY_FINISH)); } }
import com.google.common.collect.Multiset; import java.util.Arrays; import java.util.List; public class MultisetCollectorExample { public static void main(String[] args) { List<String> names = Arrays.asList("shekhar", "rahul", "shekhar"); Multiset<String> set = names.stream().collect(new MultisetCollector<>()); set.forEach(str -> System.out.println(str + ":" + set.count(str))); } }
之前也看过java 8 的相关中文书籍,效果感觉不怎么好,没有讲到本质问题,或者说本质没有讲清楚,这本是的前两章,对面向接口编程、函数式编程、lambda表达式讲的很清楚,这两章啃透彻了,后面看起来容易多了。
本人比较懒,打字太累,费时,下面是看完前两章的一些笔记照片。
相关文章推荐
- The Java IDL Development Process and the Hello World Tutorial
- Java(TM) EE 5 Tutorial, The (3rd Edition)
- The Java EE 6 Tutorial Writing Service Methods
- 继续The JavaTM Tutorial之旅。
- The Java EE 6 Tutorial Filtering Requests and Responses
- 设计: ListView 接口,and the missing read-only interfaces in java collection framework
- The JavaTM Tutorial 缓慢进行中。
- The Java EE 6 Tutorial Invoking Other Web Resources
- Where are Duke's case-studies from the Java EE 6、7 Tutorial?
- 设计: ListView 接口,and the missing read-only interfaces in java collection framework
- The Java EE 6 Tutorial Accessing the Web Context
- The Java EE 6 Tutorial Finalizing a Servlet
- 【Java Tutorial】: The Java Technology Phenomenon(Java技术现象)【官方原版教程】
- The parameters 'mainClass' for goal org.codeh aus.mojo:exec-maven-plugin:1.6.0:java are missing or
- The 10 Most Important Security Controls Missing in JavaEE--reference
- The Java EE 6 Tutorial Maintaining Client State
- The Java EE 6 Tutorial The mood Example Application
- The missing SwingApplication class in Java Swing Framework.
- The Java EE 6 Tutorial Creating and Initializing a Servlet
- 【翻译】The Java Tutorial中的Object概念