Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding to a linkedList in a HashMap<String, LinkedList>

I want to add to a linkedlist within a hashmap. ex john:--> jack-->black-->crack susan:--> sally,sammy,silly ect

Im not quite sure how to do this. Do i need a new linkedList for each name and if so how do i dynamically create one. Here is some sample 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());
        }
    }
}

Srry if this is not a good post this is my first one

like image 493
johanvdv Avatar asked Oct 20 '22 23:10

johanvdv


1 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);
}
like image 193
Alex Suo Avatar answered Oct 23 '22 08:10

Alex Suo