Skip to content

Instantly share code, notes, and snippets.

@YukiYoshikawa
Last active December 16, 2015 07:59
Show Gist options
  • Save YukiYoshikawa/5402521 to your computer and use it in GitHub Desktop.
Save YukiYoshikawa/5402521 to your computer and use it in GitHub Desktop.
package trial.yy.java8.client.stream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import java.util.stream.Collectors;
/**
* Java8 java.util.stream.Stream#collect を試すためのサンプル
* User: yy
* Date: 13/04/17
* Time: 22:23
*/
public class Java8CollectClient {
public static void main(String[] args) {
// 操作対象の文字列を格納したList
List<String> srclist = Arrays.asList("defg", "defg", "x", "xyz", "zzzzzzzz", "abc", "abcde");
// Collectors#toListを使用
List<String> destList1 = srclist.stream().filter(e -> e.length() > 3).collect(Collectors.<String>toList());
// Collectors#toCollection(ArrayList)を使用
List<String> destList2 = srclist.stream().filter(e -> e.length() > 3).collect(Collectors.toCollection(ArrayList::new));
// Collectors#toCollection(LinkedList)を使用
List<String> destList3 = srclist.stream().filter(e -> e.length() > 3).collect(Collectors.toCollection(LinkedList::new));
// Collectors#toSetを使用
Set<String> destSet1 = srclist.stream().filter(e -> e.length() > 3).collect(Collectors.<String>toSet());
// Collectors#toCollection(HashSet)を使用
Set<String> destSet2 = srclist.stream().filter(e -> e.length() > 3).collect(Collectors.toCollection(HashSet::new));
// Collectors#toCollection(TreeSet)を使用
Set<String> destSet3 = srclist.stream().filter(e -> e.length() > 3).collect(Collectors.toCollection(TreeSet::new));
// 結果(新しいCollection)の内容をまとめて出力
System.out.println("destList1: " + destList1);
System.out.println("destList2: " + destList2);
System.out.println("destList3: " + destList3);
System.out.println("destSet1: " + destSet1);
System.out.println("destSet2: " + destSet2);
System.out.println("destSet3: " + destSet3);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment