Posts

Showing posts with the label Learn Java 8 streams with example

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 ; } }

Java Program to Find the First Repeated Character in a String

Image
In this section, we will show you three different ways to find first repeated 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 = "javaworld" ; 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 ); } if ( map .get( character ) > 1 ) { System . out .println( character ); break ; } } } } Here the logic is simple, toCharArray() convert String to char Array. Iterate over Character Array and check