I have an ArrayList and another int that come from the console. I want to find the closest number larger than those int in the list using stream(). Why this doesn't work:
Scanner scn = new Scanner(System.in);
int numOfRows = scn.nextInt();
int nextNumber = scn.nextInt();
for (int i = 0; i < numOfRows; i++) {
String[] input = scn.nextLine().split(" ");
ArrayList<Integer> nums = new ArrayList<>();
for (int j = 0; j < input.length; j++) {
nums.add(Integer.parseInt(input[j]));
}
nextNumber = nums.stream().filter(x -> x > nextNumber).findFirst();
System.out.println(nextNumber);
}
Your immediate problem is trivial to fix:
Optional<Integer> oi = nums.stream()
.filter(x -> x > nextNumber)
.findFirst();
System.out.println(oi.isPresent()? "Found: "+oi.get() : "Not found");
However, if you want to write code which optimally computes what you require it to, it is not the right approach. A far better option would be this:
OptionalInt oi = Stream.of(scn.nextLine().split(" "))
.mapToInt(Integer::parseInt)
.filter(i -> i > nextNumber)
.min();
System.out.println(oi.isPresent()? "Found: "+oi.getAsInt() : "Not found");
The advantage is that you never get an ArrayList involved and don't need to autobox the integers at any step, and you actually retrieve the smallest number satisfying the criterion, not the first one.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With