Posts

Showing posts with the label Core Java

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 Maximum Occurring Character in a String

Image
In this section, we will show you how to find m aximum occurring character in a string . 1.  Using For loop and Map 2.  Using For loop 3.  Using Java 9 chars() method 4. Using  Java 8 Streams Example 1. Using For loop and Map Note:  We may have more than one character with the same maximum  occurence . This program will print all the character with maximum  occurence .   import java.util.Collections ; import java.util.HashMap ; import java.util.Map ; public class Main { public static void main ( String [] args) { String string = "java awesome dude" ; char chars [] = string .toCharArray(); Map < Character , Integer > occurrences = new HashMap<>(); for ( Character character : chars ) { Integer oldCount = occurrences .get( character ); if ( oldCount == null ) { oldCount = 0 ; } occurrences .put( character , oldCount + 1 ); } int maxValue =( Collections

Java Program to Find Maximum Occurring Word in a String

Image
In this section, we will show you how to find m aximum occurring word in a string . 1.  Using For loop and Map 2.  Using For loop 3. Using  Java 8 Streams Example 1. Using For loop and Map Note: We may have more than one key with the same maximum value. This program  will print all the keys with maximum value.   import java.util.Collections ; import java.util.HashMap ; import java.util.Map ; public class Main { public static void main ( String [] args) { String string = "Java Python Go C# Java Python Java Go C Go" ; String words [] = string .split( " " ); Map < String , Integer > occurrences = new HashMap<>(); for ( String word : words ) { Integer oldCount = occurrences .get( word ); if ( oldCount == null ) { oldCount = 0 ; } occurrences .put( word , oldCount + 1 ); } int maxValue =( Collections . max ( occurrences .values())); fo