从Java 8 2014 发布到如今,已有三年多了,JDK 8 也获得了普遍的应用,但彷佛Java 8里面最重要的特性:Lambdas和Stream APIs对不少人来讲仍是很陌生。想经过介绍Stackoverflow一些实际的问题和答案来说解在现实开发中咱们能够经过Lambdas和Stream APIs能够作些什么,以及什么是正确的姿式。在介绍那些问答以前,咱们先要对Java 8 和Stream APIs有些基本的了解,这里推荐几篇文章:html
若是你对Java 8 Lambds和Stream APIs还不是很了解,建议先把上面的几篇文章看几遍。
接下来是问答:java
1. Java 8 List<V> into Map<K, V>
有一个List<Choice> choices
, 要把它转换成一个Map<String, Choice>
, Map的Key是Choice
的名称,Value是Choice
,若是用Java 7,代码将是:git
private Map<String, Choice> nameMap(List<Choice> choices) { final Map<String, Choice> hashMap = new HashMap<>(); for (final Choice choice : choices) { hashMap.put(choice.getName(), choice); } return hashMap; }
【答案】
若是能确保Choice
的name
没有重复的github
Map<String, Choice> result = choices.stream().collect(Collectors.toMap(Choice::getName, Function.identity()));
若是name
有重复的,上面的代码会抛IllegalStateException
,要用下面的代码,api
Map<String, List<Choice>> result = choices.stream().collect(Collectors.groupingBy(Choice::getName));
2. How to Convert a Java 8 Stream to an Array?
什么是最简便的方式把一个Stream转换成数组:数组
【答案】ide
String[] strArray = Stream.of("a", "b", "c")toArray(size -> new String[size]); int[] intArray = IntStream.of(1, 2, 3).toArray();
3.Retrieving a List from a java.util.stream.Stream in Java 8
怎么把一个Stream转换成List?下面是个人尝试:学习
List<Long> sourceLongList = Arrays.asList(1L, 10L, 50L, 80L, 100L, 120L, 133L, 333L); List<Long> targetLongList = new ArrayList<>(); sourceLongList.stream().filter(l -> l > 100).forEach(targetLongList::add);
【答案】code
targetLongList = sourceLongList.stream() .filter(l -> l > 100) .collect(Collectors.toList());
这一篇的目的主要以学习前面推荐的几篇文章为主,和介绍了几个简单的问题,接下来在第二篇会介绍更多有兴趣的问答。htm
【更新】更多请参阅:Abacus-util.