- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Java Stream findAny() with examples
The findAny() method of the Java Stream returns an Optional for some element of the stream or an empty Optional if the stream is empty. Here, Optional is a container object which may or may not contain a non-null value.
Following is an example to implement the findAny() method in Java −
Example
import java.util.*; public class Demo { public static void main(String[] args){ List<Integer> list = Arrays.asList(10, 20, 30, 40, 50); Optional<Integer> res = list.stream().findAny(); if (res.isPresent()) { System.out.println(res.get()); } else { System.out.println("None!"); } } }
Output
10
Example
Let us see another example with list of strings −
import java.util.*; public class Demo { public static void main(String[] args) { List<String> myList = Arrays.asList("Kevin", "Jofra","Tom", "Chris", "Liam"); Optional<String> res = myList.stream().findAny(); if (res.isPresent()) { System.out.println(res.get()); } else { System.out.println("None!"); } } }
Output
Kevin
Advertisements