Estoy tratando de aprender java - stream. Puedo hacer una iteración / filtro / mapa / colección simple, etc.
Cuando estaba tratando de recolectar cada 3 elementos e imprimir como se muestra aquí en este ejemplo, [recolectar cada 3 elementos e imprimir y así sucesivamente...]
List<String> list = Arrays.asList("a","b","c","d","e","f","g","h","i","j"); int count=0; String append=""; for(String l: list){ if(count>2){ System.out.println(append); System.out.println("-------------------"); append=""; count=0; } append = append + l; count++; } System.out.println(append);producción:
abc ------------------- def ------------------- ghi ------------------- jNo tengo ni idea de cómo hacer esto usando stream. ¿Debo implementar mi propio recolector para lograr esto?
De hecho, puede usar un IntStream para simular la paginación de su lista.
List<String> list = Arrays.asList("a","b","c","d","e","f","g","h","i","j"); int pageSize = 3; IntStream.range(0, (list.size() + pageSize - 1) / pageSize) .mapToObj(i -> list.subList(i * pageSize, Math.min(pageSize * (i + 1), list.size()))) .forEach(System.out::println);que salidas:
[a, b, c] [d, e, f] [g, h, i] [j] Si desea generar cadenas, puede usar String.join ya que está tratando con List<String> directamente:
.mapToObj(i -> String.join("", list.subList(i * pageSize, Math.min(pageSize * (i + 1), list.size()))))Si tiene Guayaba en su proyecto, puede usar el método Iterables.partition :
import com.google.common.collect.Iterables; import com.google.common.collect.Streams; ... Stream<List<String>> stream = Streams.stream(Iterables.partition(list, 3));Puede crear su propio Collector . La forma más sencilla es llamar a Collector.of() .
Dado que su caso de uso requiere que los valores se procesen en orden, aquí hay una implementación que simplemente no admite el procesamiento en paralelo.
public static Collector<String, List<List<String>>, List<List<String>>> blockCollector(int blockSize) { return Collector.of( ArrayList<List<String>>::new, (list, value) -> { List<String> block = (list.isEmpty() ? null : list.get(list.size() - 1)); if (block == null || block.size() == blockSize) list.add(block = new ArrayList<>(blockSize)); block.add(value); }, (r1, r2) -> { throw new UnsupportedOperationException("Parallel processing not supported"); } ); }Prueba
List<String> input = Arrays.asList("a","b","c","d","e","f","g","h","i","j"); List<List<String>> output = input.stream().collect(blockCollector(3)); output.forEach(System.out::println);Producción
[a, b, c] [d, e, f] [g, h, i] [j]