Java 8 Streams, Functions and Reductions Explained

There is a relatively simple challenge to extend the vowels in a string. Here is a way to do it in Java 8:

import java.util.function.Function;

public class WordVowels {

	public static String extendVowels(String string, int i) {

		if (i < 0) {
			return "invalid";
		}

		Function<Character, String> charsFunction = (ch) -> isVowel(ch) ? multiplyChars(ch, i) : ch.toString();

		return string.chars().mapToObj(c -> (char) c).map(c -> charsFunction.apply(c)).reduce("", String::concat);

	}

	private static boolean isVowel(char ch) {
		switch (Character.toLowerCase(ch)) {
		case 'a':
		case 'e':
		case 'i':
		case 'o':
		case 'u':
			return true;
		default:
			return false;
		}
	}

	private static String multiplyChars(char ch, int i) {

		StringBuilder s = new StringBuilder();

		for (int j = 0; j <= i; j++) {
			s.append(ch);
		}
		return s.toString();
	}
}

In the above I’ve tried to make the code as short as possible while still ensuring it’s readable and conforming to the clean code rules.

All of that could be written without streams and functions but it would be much more ugly and long, probably with nested loops and complex conditions.

For code readability I’ve added additional methods which should explain what is being done.

Comments

So empty here ... leave a comment!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Sidebar



%d bloggers like this: