從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.