Posts

Showing posts with the label Split a comma separated String

Java Program to Find Frequency of each Word in a String

Image
In this section, we will show you three different ways to find frequency of each word in a given String in Java. 1.  Using For loop and Map  2. Using Java 8 Streams 3. 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 string = "Java Python Go C# Java Python Java Go C" ; //Split the string into words based on whitespace String words [] = string .split( " " ); Map < String , Integer > occurrences = new HashMap<>(); //Iterate through String array for ( String word : words ) { Integer oldCount = occurrences .get( word ); if ( oldCount == null ) { oldCount = 0 ; } occurrences .put( word , oldCount + 1 ); } System . out .println( occurrences ); } } 1.  split() method in Java splits a strin...

Split a String in Java - 5 different ways

Image
In this section, we will show you five different ways to split a String in Java based on  the delimiter. 1. Using  String.split() The split method in Java splits a string into substrings using a delimiter that is specified using a regular expression. 1. This method returns an array of strings. 2. This method takes a regex string as a parameter. Split a whitespace separated String //Split by a whitespace String input = "yellow black green orange" ; String [] colors = input .split( " " ); Split a comma separated String //Split by a comma String input = "yellow,black,green,orange" ; String [] colors = input .split( " , " ); Split a dot separated String //Split by a dot String input = "123.12.12.1" ; String [] splitted = input .split( " \\ . " ); Split and Trim a comma separated String String input = " yellow,black ,green, orange" ; String [] colors = input .trim().split( " \\ s*, \\ s* " ); trim() method rem...