![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
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
Stream sorted() in Java
The Stream sorted() in Java returns a stream consisting of the elements of this stream, sorted according to natural order.
Following is the syntax −
Stream<T> sorted()
Here, Stream is an interface in java.util.stream and <T> is the type parameter in stream. This method returns the new stream.
Following is an example to implement the sorted() method in stream class −
Example
import java.util.*; public class Demo { public static void main(String[] args) { List<String> list = Arrays.asList("Jack", "Tom", "Kevin", "David", "Tim", "Nathan", "John", "Ryan", "Robbie"); System.out.println("Sorted stream... "); list.stream().sorted().forEach(System.out::println); } }
Output
The sorted stream is : David Jack John Kevin Nathan Robbie Ryan Tim Tom
Example
Let us see another example to sort stream −
import java.util.stream.Stream; public class Demo { public static void main(String[] args) { Stream<Integer> stream = Stream.of(50, 20, 12, 30, 5, 10, 15, 35, 60); System.out.println("Sorted stream.."); stream.sorted().forEach(System.out::println); } }
Output
Sorted stream.. 5 10 12 15 20 30 35 50 60
Advertisements