Click here to Skip to main content
15,892,298 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Is there a native data structure in java that accepts key value pairs and allows duplicates? I want to store occurence of a word as key and word itself as a value. I'll insert them into a db later.

What I have tried:

String str, word;
		int wordsLen, i, count, j, k;
		Map<Integer, String> map = new HashMap<>();
		Scanner s = new Scanner(System.in);

		System.out.print("Enter the String: ");
		str = s.nextLine();

		String words[] = str.split(" ");
		wordsLen = words.length;

		System.out.println("\n--occurences--");
		for (i = 0; i < wordsLen; i++) {
			word = words[i];
			count = 1;
			for (j = i + 1; j < wordsLen; j++) {
			    if (word.equals(words[j]))  {
					count++;
					for (k = j; k < (wordsLen - 1); k++) {
						words[k] = words[k + 1];
					}
					wordsLen--;
					j--;
				}
			}
			map.put(count, word);
			System.out.println(word + " occurs " + count);
			count = 0;
		}
		System.out.println(map);
}
Posted
Updated 26-Mar-22 8:06am

Have a look at What is a Multimap in Java?[^].
If you don't want to use the Guava library, alternatives like Map<K, List<V>> are proposed.
 
Share this answer
 
I'd just create a class to hold the values, and store all instances of that. Easier to read, easier to maintain.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900