Parse a MultipartFile line by line and Count the total number of lines in Java

563 Views Asked by At

I am trying to parse a MultipartFile line by line, and also count the total number of lines as it goes. Here's the snippet:

        var inputStream = file.getInputStream();
        var stream = new BufferedReader(
                new InputStreamReader(inputStream, StandardCharsets.UTF_8)
        ).lines();

        var totalTargetCount = 0l;

        stream.forEach(line -> {
            processTheLine(line);
            totalTargetCount++;
        });

But this gives the error Variable used in lambda expression should be final or effectively final What should I do in this case?

1

There are 1 best solutions below

0
On

Found this that shows how to use a counter in stream's foreach, and I quote:

Method 1: Using Array

// define a list
List<Integer> numbers = List.of(5,67,89,23,12,99,478,900);
int[] counter = new int[1];
// iterate using forEach 
numbers.forEach(num -> {
  // check if list element is greater than 50 
  if(num > 50) {
    counter[0]++;
  }
});
System.out.println("Number of integers greater than 50 = " +counter[0]);

Method 2: Using AtomicInteger

// define a list
List<Integer> numbers = List.of(5,67,89,23,12,99,478,900);
AtomicInteger counter = new AtomicInteger();
// iterate using forEach
numbers.forEach(num -> {
   // check if list element is greater than 50 
   if(num > 50) {
      counter.getAndIncrement();
   }
});
System.out.println("Number of integers greater than 50 = "+counter.get());

Method 3: Using AtomicReference

// define a list
List<Integer> numbers = List.of(5,67,89,23,12,99,478,900);
AtomicReference<Integer> counter = new AtomicReference<>(0);
// iterate using forEach
numbers.forEach(num -> {
   // check if list element is greater than 50
   if(num > 50) {
      counter.getAndUpdate(value -> value + 1);
   }
});
System.out.println("Number of integers greater than 50 = "+counter.get());