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

Java - Find Largest and Smallest word in a String

Image
In this section, we will show you how to find longest word in as given String in Java . 1.  Using For loop 2. Using  Java 8 Streams Find Largest Word: Using For loop public class Main { public static void main ( String [] args) { String inputString = "Java is an awesome programming language" ; String [] strArray = inputString .split( " " ); String maxlengthWord = "" ; for ( int i = 0 ; i < strArray . length ; i ++){ if ( strArray [ i ].length() > maxlengthWord .length()){ maxlengthWord = strArray [ i ]; } } System . out .println( maxlengthWord ); } } Here the logic is simple, First, declare the string as a string literal. Using the split() method, split the string based on whitespace. It returns an array of strings. Declare an empty string; later, we use it to accumulate the longest word. Iterate over the string array and check whether the length of the [

Java Program to Find the First Non Repeating Character in a String

Image
In this section, we will show you three different ways to find first non repeating character in a given String in Java. 1.  Using For loop and Map 2.  Using Java 9 chars() method 3. Using  Java 8 Streams Example 1. Using For loop and Map import java.util.LinkedHashMap ; import java.util.Map ; public class Main { public static void main ( String [] args) { String str = "america" ; Map < Character , Integer > map = new LinkedHashMap<>(); for ( Character character : str .toCharArray()) { if ( map .containsKey( character )) { map .put( character , map .get( character ) + 1 ); } else { map .put( character , 1 ); } } for ( Map . Entry < Character , Integer > entry : map .entrySet()) { if ( entry .getValue()== 1 ) { System . out .println( entry .getKey()); break ; } }