Java implementation of Trigrams Kata.
Main.java
import org.apache.commons.collections4.MultiValuedMap; import org.apache.commons.collections4.multimap.ArrayListValuedHashMap; import java.util.ArrayList; import java.util.List; import java.util.Random; public class Main { public static void main(String[] args) { String text = "I wish I may I wish I might"; String[] words = text.split(" "); MultiValuedMap<String, String> trigrams = new ArrayListValuedHashMap<>(); for (int i = 0; i < words.length - 2; ++i) { trigrams.put(words[i] + " " + words[i + 1], words[i + 2]); } String newText = "I may"; String key = newText; Random random = new Random(); while (trigrams.containsKey(key)){ List<String> list = new ArrayList<>(trigrams.get(key)); String nextText = list.get(random.nextInt(list.size())); newText += " " + nextText; String[] keyList = key.split(" "); key = keyList[1] + " " + nextText; } System.out.println(newText); } }