简体   繁体   中英

Convert Stream of Collection<String[]> to List<String>[]

I have a piece of code:

table.stream().filter(row -> !hash.containsKey(row[keyColumnNumber]))
.map(row -> row[keyColumnNumber]).map(hash::get)

The last step: .map(hash::get) returns Collection<String[]> . and as a result I need to collect all of that to List.

.collect(Collectors.toList())

returns List> what is expected, but

.flatMap(Stream::of).collect(Collectors.toList()).collect(Collectors.toList())

returns the same result.

You can use flatMap like so :

List<String> list = table.stream()
        .map(row -> hash.get(row[keyColumnNumber]))
        .filter(Objects::nonNull)
        .flatMap(Arrays::stream)
        .collect(Collectors.toList());

If

table.stream().filter(row -> !hash.containsKey(row[keyColumnNumber]))
.map(row -> row[keyColumnNumber]).map(hash::get)

returns a Stream<Collection<String[]>> and you require a List<String[]> , you do need flatMap :

List<String[]> result = table.stream()
        .filter(row -> !hash.containsKey(row[keyColumnNumber]))
        .map(row -> row[keyColumnNumber])
        .map(hash::get) // Stream<Collection<String[]>>
        .flatMap(Collection::stream) // Stream<String[]>
        .collect(Collectors.toList()); // List<String[]>

It should be possible to join the map and flatMap calls into a single flatMap , as Aomine commented:

List<String[]> result = table.stream()
        .filter(row -> !hash.containsKey(row[keyColumnNumber]))
        .flatMap(row -> hash.get(row[keyColumnNumber]).stream()) // Stream<String[]>
        .collect(Collectors.toList()); // List<String[]>

try this. i hope it can solve...

List<String> list = table.stream().filter(row -> !hash.containsKey(row[keyColumnNumber]))
  .map(row -> row[keyColumnNumber]) 
  .flatMap(x -> Arrays.stream(hash.get()))//<<-----------------
  .collect(Collectors.toList());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM