Posts

Showing posts with the label Learn Java 8 streams with example

Java 8 Stream - Sort HashMap based on Keys and Values

Image
By default, Java HashMap doesn’t maintain any order. However, if you need to sort the HashMap, we sort the HashMap explicitly based on your requirements. So, in this section, let’s understand how to sort the hashmap according to the keys and values by using Java 8’s Stream API. 1. Sort HashMap by keys in natural order import java.util. *; import java.util.stream.Collectors ; public class Main { public static void main ( String [] args) { Map < Integer , String > map = new HashMap<>(); map .put( 44 , "Java" ); map .put( 66 , "Ada" ); map .put( 29 , "Go" ); map .put( 98 , "Kotlin" ); map .put( 11 , "C" ); map .put( 125 , "Rust" ); Map < Integer , String > sortedMap = map .entrySet() .stream() .sorted( Map . Entry . comparingByKey ()) .collect( Collectors . toMap ( Map . Entry ::get

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Example 1: Java 8 program to print odd numbers from a List   import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; /*Java 8 Program to find Odd Numbers from a List*/ public class DriverClass { public static void main( String [] args) { List < Integer > numbers = Arrays. asList( 1 , 4 , 8 , 40 , 11 , 22 , 33 , 99 ); List < Integer > oddNumbers = numbers.stream(). filter(o -> o % 2 != 0 ). collect(Collectors.toList()); System.out.println(oddNumbers); } } 1. Initialize List using Arrays.asList() method. Java's built-in Arrays.asList() method converts an array into a list. This method takes an array as an argument and returns a List object. 2.  Java List interface provides stream() method which returns a sequential Stream with list of Integer as its source. 3. The Java stream filter() method allow

Java 8 Stream – How to sort a List with stream.sorted()

In this section, we will show you how to sort list using stream.sorted() in Java 8. 1. List 1.1 Sort a List in natural order. import java.util.Arrays ; import java.util.Comparator ; import java.util.List ; import java.util.stream.Collectors ; public class Main { public static void main ( String [] args) { List < String > list = Arrays . asList ( "8" , "B" , "A" , "1" , "Z" , "Y" , "2" , "b" , "d" ); List < String > sortedList1 = list .stream() .sorted( Comparator . naturalOrder ()) .collect( Collectors . toList ()); System . out .println( sortedList1 ); List < String > sortedList2 = list .stream() .sorted((o1,o2)-> o1.compareTo(o2)) .collect( Collectors . toList ()); System . out .println( sortedList2 ); List < String > sortedList3 = list .stream(). sorted().