Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,560 questions

51,419 answers

573 users

How to group words by first letter in Java

1 Answer

0 votes
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]}

*/

 



answered 13 hours ago by avibootz
edited 12 hours ago by avibootz
...