Java 8 – How to remove last comma (,) from String ?

In this article, we will learn how to remove last comma (,) from a String using String‘s substring() method and Java 8 Stream

Remove last comma (,) from String :

  1. Using Java 1.7 version
  2. Using Java 1.8 version

1. Java 1.7 – Remove last comma (,) :

  • String‘s substring() method returns partial String which accepts 2 input-arguments viz., start-index (inclusive) & end-index (exclusive)
  • To remove last character i.e.; comma (,) pass 0 (zero) as start-index & (String length – 1) as end-index

RemoveLastCommaInString.java

package in.bench.resources.java8.string.methods;

public class RemoveLastCommaInString {

	public static void main(String[] args) {

		// 1. test string with commas
		String str = "q,w,e,r,t,y,";


		// 1.1 print to console
		System.out.println("Original String :- \n" + str);


		// 2. remove last comma using String.substring() method
		str = str.substring(0, str.length()-1);


		// 2.1 print to console
		System.out.print("\nAfter removing last comma :- \n" + str);
	}
}

Output:

Original String :- 
q,w,e,r,t,y,

After removing last comma :- 
q,w,e,r,t,y

2. Java 1.8 – Remove last comma (,) :

  • There is a list of Strings with last character as comma (,) which needs to be removed using Java 8 Streams
    1. Get the stream from the list
    2. Then map each string by removing last character comma (,) using String‘s substring() method
    3. Finally, iterate/print comma (,) removed strings to console using Stream.forEach() method

RemoveLastCommaInStringUsingJava8.java

package in.bench.resources.java8.string.methods;

import java.util.ArrayList;
import java.util.List;

public class RemoveLastCommaInStringUsingJava8 {

	public static void main(String[] args) {

		// 1. List of Strings
		List<String> stringsWithCommas = new ArrayList<>();


		// 1.1 add strings to List
		stringsWithCommas.add("q,w,e,r,t,y,");
		stringsWithCommas.add("a,s,d,f,g,h,");
		stringsWithCommas.add("z,x,c,v,b,n,");
		stringsWithCommas.add("1,2,3,4,5,6,");
		stringsWithCommas.add("b,e,n,c,h,");


		// 1.2 print to console
		System.out.println("Original List of String :- \n");
		stringsWithCommas.forEach(str -> System.out.println(str));


		// 2. remove last comma using String.substring() method
		System.out.println("\n\nList of String after removing last Comma :- \n");
		stringsWithCommas
		.stream()
		.map(str -> str.substring(0, str.length()-1))
		.forEach(str -> System.out.println(str));
	}
}

Output:

Original List of String :- 

q,w,e,r,t,y,
a,s,d,f,g,h,
z,x,c,v,b,n,
1,2,3,4,5,6,
b,e,n,c,h,


List of String after removing last Comma :- 

q,w,e,r,t,y
a,s,d,f,g,h
z,x,c,v,b,n
1,2,3,4,5,6
b,e,n,c,h

Related Articles :

References :

Happy Coding !!
Happy Learning !!

Java 8 – How to count length of last word in a String ?
Java 8 – How to remove special characters from String ?