Twi:
Eu tenho o seguinte código que poderia ser muito mais simples usando Java 8 fluxo de API:
List<List<String>> listOfListValues;
public List<String> getAsFlattenedList() {
List<String> listOfValues= new ArrayList<>();
for (List<String> value: listOfListValues) {
listOfValues.add(String.valueOf(value));
}
return listOfValues;
}
I procurou uma solução no SO e encontrei este:
listOfListValues.stream()
.flatMap(List::stream)
.collect(Collectors.toList());
Mas isso não fazer o mesmo que eu quero.
Roland:
Você precisa de apenas um "simples" map
aqui:
List<List<String>> listOfListValues;
public List<String> getAsFlattenedList() {
return listOfListValues.stream()
.map(String::valueOf)
.collect(toList());
}
flatMap
é bastante usado para transformar um Stream
para o outro, o que faz sentido se você precisar de mais entradas ou menos, em seguida, atualmente disponível (ou apenas um recém-mapeada Stream
para filtrar / map / etc-lo ainda mais para baixo), por exemplo:
contar todas as cordas únicas de todas as listas:
listOfListValues.stream() .flatMap(List::stream) // we want to count all, also those from the "inner" list... .distinct() .count()
entradas truncamento depois de um certo tamanho:
listOfListValues.stream() .flatMap(list -> { if (list.size() > 3) // in this case we use only some of the entries return Stream.concat(list.subList(0, 2).stream(), Stream.of("...")); else return list.stream(); }) .collect(Collectors.toList());
achatamento valores de um mapa para várias chaves interessados:
Map<Key, List<Value>> map = new HashMap<>(); Stream<Value> valueStream = interestedKeys.stream() .map(map::get) .flatMap(List::stream);