import java.util.ArrayList;
import java.util.HashMap;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
public class GroupWordsProgram {
public static void main(String[] args) {
// List of words to group
List<String> words = Arrays.asList(
"Python", "JavaScript", "C", "Java", "C#", "PHP", "C++", "Pascal", "SQL", "Rust"
);
Map<Character, List<String>> grouped = groupByFirstLetter(words);
// Print each group
for (Map.Entry<Character, List<String>> entry : grouped.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
// Print the whole map
System.out.println(grouped);
}
/**
* Groups a list of words by their first letter.
*/
public static Map<Character, List<String>> groupByFirstLetter(List<String> words) {
Map<Character, List<String>> groupWords = new HashMap<>();
// Loop through each word
for (String word : words) {
char firstLetter = word.charAt(0); // Extract first letter
// Automatically create a new list if the key doesn't exist
groupWords.computeIfAbsent(firstLetter, k -> new ArrayList<>()).add(word);
}
return groupWords;
}
}
/*
run:
P: [Python, PHP, Pascal]
R: [Rust]
S: [SQL]
C: [C, C#, C++]
J: [JavaScript, Java]
{P=[Python, PHP, Pascal], R=[Rust], S=[SQL], C=[C, C#, C++], J=[JavaScript, Java]}
*/