Saturday 30 January 2021

Java12: Transform a string

‘transform’ method takes a function as argument and apply this function to the string and return the result.

 

Signature

public <R> R transform(Function<? super String, ? extends R> f)

 

Example 1: Convert string to upper case and prepend 5 spaces.

str.transform(s -> s.toUpperCase().indent(5));

 

Example 2: Display a welcome message by converting user name to uppercase.

name.transform(s -> "Welcome Mr. " + s.toUpperCase());

 

Find the below working application.

 

StringTransformExample1.java

package com.sample.app.strings;

public class StringTransformExample1 {

	public static void main(String args[]) {
		String str = "aa123ajbd134aa";

		int noOfDigits = str.transform((s) -> {
			int count = 0;

			for (int i = 0; i < s.length(); i++) {
				if (Character.isDigit(s.charAt(i))) {
					count++;
				}
			}
			return count;
		});

		String stringInUpperCase = str.transform(s -> s.toUpperCase());
		String stringInUpperCasePlus5SpacesIndentation = str.transform(s -> s.toUpperCase().indent(5));

		String name = "Krishna";
		String welcomeMessage = name.transform(s -> "Welcome Mr. " + s.toUpperCase());

		System.out.println("noOfDigits : " + noOfDigits);
		System.out.println("stringInUpperCase : " + stringInUpperCase);
		System.out.println("stringInUpperCasePlus5SpacesIndentation : " + stringInUpperCasePlus5SpacesIndentation);
		System.out.println("welcomeMessage : " + welcomeMessage);
	}

}

Output

noOfDigits : 6
stringInUpperCase : AA123AJBD134AA
stringInUpperCasePlus5SpacesIndentation :      AA123AJBD134AA

welcomeMessage : Welcome Mr. KRISHNA

 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment