Posts

Showing posts with the label Core Java

Java Program to Find Duplicate Characters in a String - 5 Ways

Image
In this section, we will show you five different ways to find duplicate characters in a given String in Java. 1.  Using For loop  2. Using  Enhanced for loop 3. Using Java 9 chars() method 4. Using Java 8 Streams 5. Using Google Guava MultiSet Example 1. Using For loop import java.util.HashMap ; import java.util.HashSet ; import java.util.Map ; import java.util.Set ; public class Main { public static void main ( String [] args) { String str = "hellojava" ; Map < Character , Integer > occurrences = new HashMap<>(); Set < Character > characterSet = new HashSet<>(); for ( int i = 0 ; i < str .length(); i ++) { char c = str .charAt( i ); if ( occurrences .containsKey( c )) { int count = occurrences .get( c ); occurrences .put( c , ++ count ); characterSet .add( c ); } else { occurrences .put( c , 1 ); }

Java Program to Find Frequency of each Character in a String - 5 Ways

Image
In this section, we will show you five different ways to find frequency of each Character in a given String in Java. 1.  Using For loop and Map  2. Using  Enhanced for loop and Map 3. Using Java 9 chars() method 4. Using Java 8 Streams 5. Using Google Guava MultiSet Example 1. Using For loop and Map  import java.util.HashMap ; import java.util.Map ; public class Main { public static void main ( String [] args) { String str = "hello java hello java" ; Map < Character , Integer > occurrences = new HashMap<>(); for ( int i = 0 ; i < str .length(); i ++) { char c = str .charAt( i ); if ( occurrences .containsKey( c )) { int count = occurrences .get( c ); occurrences .put( c , ++ count ); } else { occurrences .put( c , 1 ); } } System . out .println( occurrences ); } } Here we iterate through string chars.  Check whether map

Java - Convert the first character of each word in a string to Lowercase

Image
In this section, we will show five different ways to  convert the first character of each word in a string to Lowercase in Java. 1. Using For loop and toLowerCase() method 2. Using Java 8 Streams 3. Using regex and replaceAll() method 4. Using Apache Commons Text 5. Using Google Guava 1. Using For loop and  toLowerCase() method public class Main { public static void main ( String [] args) { String string = "JAVA IS AWESOME" ; String [] arr = string .split( " " ); StringBuilder stringBuilder = new StringBuilder (); for ( int i = 0 ; i < arr . length ; i ++) { stringBuilder .append( Character . toLowerCase ( arr [ i ].charAt( 0 ))) .append( arr [ i ].substring( 1 )).append( " " ); } String result = stringBuilder .toString(); System . out .println( result ); } } Here we are using  split()  split the string based on whitespace. It returns an Array of St