javastreamjava-stream

How to collect List<String> to List<String> using streams in java?


I have listData (List<String>) and a getList method that accepts a String as an argument (e.g. "java") and returns a List<String> (e.g. ["j","a","v","a"]). I need to collect these lists to a single List. I tried addAll, and it works fine:

List<String> listData = Arrays.asList("java","Stream","laMbdA");
List<String> resultList = new ArrayList<>();

listData.stream()
        .map(this::getList)  // acccepts String as an argument and returns List<String>
        .forEach(resultList::addAll);

If I try Collectors.toList(), I am getting a List<List<String>>

 listData.stream()
         .map(this::getList)
         .collect(Collectors.toList());

Is there any method in Collectors which I could use instead of addAll?


Solution

  • You need flatMap:

    List<String> resultList =
        listData.stream()
                .flatMap(s -> getList(s).stream())
                .collect(Collectors.toList());