n
-size chunks Java 8 Stream API. Collectors.groupingBy()
, - Collection<List<String>>
, (, ).
:
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
public class ReadFileWithStream {
public static void main(String[] args) throws IOException {
final Path path = Paths.get(ReadFileWithStream.class.getResource("/input.txt").toURI());
final AtomicInteger counter = new AtomicInteger(0);
final int size = 4;
final Collection<List<String>> partitioned = Files.lines(path)
.collect(Collectors.groupingBy(it -> counter.getAndIncrement() / size))
.values();
partitioned.forEach(System.out::println);
}
}
( ), , - :
[0, 0, 0, 2]
[0, -3, 2, 0]
[1, -3, -8, 0]
[2, -12, -11, -11]
[-8, -1, -8, 0]
[2, -1, 2, -1]
... and so on
Collectors.groupingBy()
. Collectors.toList()
, List<String>
, Collection<List<String>>
.
Let's say I want to read 4-dimensional pieces, and I want to sum all the numbers in a piece. In this case, I will use Collectors.summingInt()
both my descending function and the return result Collection<Integer>
:
final Collection<Integer> partitioned = Files.lines(path)
.collect(Collectors.groupingBy(it -> counter.getAndIncrement() / size, Collectors.summingInt(Integer::valueOf)))
.values();
Conclusion:
2
-1
-10
-32
-17
2
-11
-49
... and so on
And last but not least. Collectors.groupingBy()
returns a map where values are grouped by specific keys. That is why at the end we call Map.values()
to get the set of values contained on this map.
Hope this helps.