Implement count variable with java lambda expression

I have a question about lambda expressions. I have a couple of classes that should contain String and int.

The pair gets the string from the file. and int is the line number. So far I have this:

 Stream<String> lineNumbers = Files.lines(Paths.get(fileName));
    List<Integer> posStream = Stream.iterate(0, x -> x + 1).limit(lineNumbers.count()).collect(Collectors.toList());
    lineNumbers.close();
    Stream<String> line = Files.lines(Paths.get(fileName));
    List<Pair> pairs = line.map((f) -> new Pair<>(f,1))
            .collect(Collectors.toList());
    pairs.forEach(f -> System.out.println(f.toString()));
    line.close();

How can I now enter file numbers in pairs? Is there a lambda expression that can accomplish this? Or do I need something else?

+4
source share
3 answers

There are several ways to do this. The counter technique proposed by Saloparenator's answer can be implemented as follows, using AtomicIntegeras a mutable counter object and assuming an obvious class Pair:

List<Pair> getPairs1() throws IOException {
    AtomicInteger counter = new AtomicInteger(0);
    try (Stream<String> lines = Files.lines(Paths.get(FILENAME))) {
        return lines.parallel()
                    .map(line -> new Pair(line, counter.incrementAndGet()))
                    .collect(toList());
    }
}

, , , . , . Files.lines , , incrementAndGet(). , . , , , , .

. , , . :

static List<Pair> getPairs2() throws IOException {
    List<String> lines = Files.readAllLines(Paths.get(FILENAME));
    return IntStream.range(0, lines.size())
                    .parallel()
                    .mapToObj(i -> new Pair(lines.get(i), i+1))
                    .collect(toList());
}
+7

ZIP-

( , java8 , , )

java8

0
int cnt = 1;
List<Pair> pairs = line.map((f) -> new Pair<>(f,cnt++))
                       .collect(Collectors.toList());

I have not tried it yet, but I can work.

-1
source

Source: https://habr.com/ru/post/1584516/