Skip to content

Instantly share code, notes, and snippets.

@ytnk531
Created August 8, 2018 15:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ytnk531/e1d485d6a03334a003cd566217101967 to your computer and use it in GitHub Desktop.
Save ytnk531/e1d485d6a03334a003cd566217101967 to your computer and use it in GitHub Desktop.
JavaのflatMapがちょっと気に食わない
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class FlatMapSample {
public static void main(String[] arg) {
List<Integer> listA = Arrays.asList(1, 3, 5);
List<Integer> listB = Arrays.asList(2, 4, 6, 8);
List<Integer> listC = Arrays.asList(7, 9, 10);
// リストのリスト
List<List<Integer>> listOfList = Arrays.asList(listA, listB, listC);
System.out.println("listOfList=" + listOfList);
// output: listOfList=[[1, 3, 5], [2, 4, 6, 8], [7, 9, 10]]
// 中の数字を取り出してリストを作れる
List<Integer> list = listOfList.stream()
.flatMap(List::stream) // .flatMap(l -> l.stream())と同じ
.collect(Collectors.toList());
System.out.println("list=" + list);
// output: list=[1, 3, 5, 2, 4, 6, 8, 7, 9, 10]
// もちろん中間操作もできる
List<Integer> sortedList = listOfList.stream()
.flatMap(List::stream)
.sorted()
.collect(Collectors.toList());
System.out.println("sortedList=" + sortedList);
// output: sortedList=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
// 参考: Streamを使わずに書くとこんなん
List<Integer> listFor = new ArrayList<>();
for (List<Integer> l : listOfList) {
for (Integer integer : l) {
listFor.add(integer);
}
}
System.out.println("listFor=" + sortedList);
// output: listFor=[1, 3, 5, 2, 4, 6, 8, 7, 9, 10]
List<Integer> sortedListFor = new ArrayList<>();
for (List<Integer> l : listOfList) {
for (Integer integer : l) {
sortedListFor.add(integer);
}
}
sortedList.sort(null);
System.out.println("sortedListFor=" + sortedListFor);
// output: sortedListFor=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment