Home  >  Java 8

Java 8 Stream: findAny, findFirst, limit, max and min Example

By Arvind Rai, November 20, 2014
On this page we will learn the use of java 8 stream findAny, findFirst, limit, max and min method example. findAny, findFirst, max and min methods return Optional instance and limit method returns stream instance.

Stream.findAny

findAny() method can find any element from stream. It returns Optional instance. If there is no data in stream, it returns empty Optional instance.
FindAnyDemo.java
package com.concretepage.util.stream;
import java.util.Arrays;
import java.util.List;
public class FindAnyDemo {
    public static void main(String[] args) {
        List<String> list = Arrays.asList("AA","BB","CC");    
        list.stream().findAny().ifPresent(s->System.out.println(s));
    }
} 
Find the output.
AA 

Stream.findFirst

findFirst() returns first element of the stream and if stream has defined no encounter order, then it may return any element. If stream is empty, it returns empty Optional instance.
FindFirstDemo.java
package com.concretepage.util.stream;
import java.util.Arrays;
import java.util.List;
public class FindFirstDemo {
    public static void main(String[] args) {
        List<String> list = Arrays.asList("XX","YY","ZZ");    
        list.stream().findFirst().ifPresent(s->System.out.println(s));
    }
} 
Find the output.
XX 

Stream.limit

limit() method of stream API returns stream instance with the given number of element in limit as an argument. limit() method selects the elements from start. We need to pass a max value and it returns the stream up to the max number of elements.
LimitDemo.java
package com.concretepage.util.stream;
import java.util.Arrays;
import java.util.List;
public class LimitDemo {
    public static void main(String[] args) {
        List<String> list = Arrays.asList("AA","BB","CC","DD","EE");    
        list.stream().limit(3).forEach(s->System.out.println(s));
    }        
} 
Find the output.
AA
BB
CC 

Stream.max() and Stream.min()

max() method returns maximum element on the basis of given comparator. It returns Optional instance. min() method returns minimum element on the basis of given comparator. It returns Optional instance.
StreamMaxMin.java
package com.concretepage;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
public class StreamMaxMin {
	public static void main(String[] args) {
		List<String> list = Arrays.asList("G","B","F","E");
		String max = list.stream().max(Comparator.comparing(String::valueOf)).get();
		System.out.println("Max:"+ max);
		String min = list.stream().min(Comparator.comparing(String::valueOf)).get();
		System.out.println("Min:"+ min);		
	}
}  
Find the output.
Max:G
Min:B 
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS


©2019 concretepage.com | Privacy Policy | Contact Us