Adding to a linked List in a HashMap <String, LinkedList>

I want to add a linked list to a hash file. ex john: β†’ jack β†’ black β†’ crack susan: β†’ sally, sammy, silly ect

I'm not quite sure how to do this. Do I need a new linked List for each name, and if so, how do I dynamically create it. Here is an example of the code I made to try.

import java.util.*; import java.io.*; public class test { public static void main(String args[]) throws FileNotFoundException{ HashMap<String, LinkedList<String>> testMap = new HashMap<String, LinkedList<String>>(); File testFile = new File("testFile.txt"); Scanner enterFile = new Scanner(testFile); String nextline = ""; LinkedList<String> numberList = new LinkedList<String>(); int x = 0; while(enterFile.hasNextLine()){ nextline = enterFile.nextLine(); testMap.put(nextline.substring(0,1),numberList); for(int i = 1; i < nextline.length() - 1; i++){ System.out.println(nextline); testMap.put(nextline.substring(0,1),testMap.add(nextline.substring(i,i+1))); } x++; } LinkedList<String> printHashList = new LinkedList<String>(); printHashList = testMap.get(1); if(printHashList.peek() != "p"){ System.out.println(printHashList.peek()); } } } 

Happiness, if this is not a good post, this is my first

+5
source share
2 answers
 public void putToMap(String name) { String firstLetter = name.substring(0, 1); List<String> names = testMap.get(firstLetter); if (names == null) { names = new LinkedList<String> (); testMap.put(firstLetter, names); } names.add(name); } 
+2
source

Alex's answer is a general (and easiest) solution to your problem, and one that you should choose as your answer (if it changes it in accordance with my comment), but just wanted to tell you that another solution use LinkedListMultiMap (which is a class in the Guava library).

LinkedListMultiMap is an easy way to manage list maps (but carries the additional overhead of the Guava library). You can add several values ​​individually for each key, which, I believe, is your desired behavior.

+1
source

Source: https://habr.com/ru/post/1205148/


All Articles