6
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Java8 リストを結合する

Posted at

Java8 でリストを結合(マージ)する方法。調べたら3つありました。

import java.util.*;
import java.util.stream.*;

class Main {
    public static void main(String[] args) {
        List<String> list1 = Arrays.asList("Apple", "Banana", "Ctrus");
        List<String> list2 = Arrays.asList("Drian", "Elderberry");
        
        // (1) http://blog.64p.org/entry/2014/11/21/123447
        List<String> newList1 = Stream.concat(list1.stream(), list2.stream())
                                      .collect(Collectors.toList());
        System.out.println(newList1);
        
        // (2) http://simplesandsamples.com/list-join.java.html
        List<String> newList2 = new ArrayList<>();
        newList2.addAll(list1);
        newList2.addAll(list2);
        System.out.println(newList2);
        
        // (3) https://ja.stackoverflow.com/questions/8232/stream%E3%81%A7%E3%83%AA%E3%82%B9%E3%83%88%E3%81%AE%E7%B5%90%E5%90%88%E3%81%8C%E3%81%97%E3%81%9F%E3%81%84
        List<List<String>> outer = Arrays.asList(list1, list2);
        List<String> newList3 = outer.stream()
            .flatMap(lst -> lst.stream())
            .collect(Collectors.toList());
        System.out.println(newList3);
    }
}
6
2
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?