Find a number in a list of numbers using Java8 sterams

I have a list of numbers

List<Integer> tensOfMinutes = Arrays.asList(10, 20, 30, 40, 50, 60);

I am trying to determine if the int input is Integer minutes;between any two members of the array above.

Example: for input Integer minutes = 23;I expect to get 20 as an answer.

Any ideas on how to accomplish this, iterating the tenOfMinutes stream?

+4
source share
2 answers

You can do it as follows:

List<Integer> l = Arrays.asList(10, 20, 30, 40, 50, 60)
        .stream()
        .filter( (i) -> i<23 )
        .collect(Collectors.toList());
System.out.println( l.get( l.size() - 1 ) );

You filter out all elements in excess 23and you print the last of the remaining elements.

It would be simpler with the help of the function dropWhilethat we have in Java 9, Scala and Haskell:

https://docs.oracle.com/javase/9/docs/api/java/util/stream/Stream.html#dropWhile-java.util.function.Predicate-


Holger

    Stream<Integer> stream = Arrays.asList(10, 20, 30, 40, 50, 60).stream();
    stream.filter( i -> i<23 )
      .reduce( (a,b) -> b )
      .ifPresent(System.out::println);

lambda (a,b) -> b, , ifPresent, .

+5

, :

int previous=0
for(Integer number : tensOfMinutes)
    if(number<=numberToFind)
        previous=number;

, , previous. , . ,

-2

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


All Articles