Search code examples
javalistdictionarymultimap

How to keep adding values to a key that already exists, when the values are in an ArrayList? Input is coming in from a scanner to create a TreeMap


I am trying to receive input from a user where each line must consist of some text (a key), followed by a tab character, followed by a double literal (a value), followed by a newline.

If the user is allowed to keep entering the same key, followed by /t, then a different value and /n, how can I write a program that keeps adding the value to the same key in a tree map?

Each key has an ArrayList, which is where I get stuck because I don't know how to keep adding to an array list for different lines/keys.

This is what I have so far:

    TreeMap<String, ArrayList<Double>> categoryMap = new TreeMap<>();

    Double val = 0.0;
    String inputKey = "";

    System.out.println("Welcome, please enter text");
    Scanner scn = new Scanner(System.in);
    dataSource = scn;

    try
    {
        // adds all words of input to a string array
        while (dataSource.hasNextLine())
        {
            ArrayList<Double> valueMap = new ArrayList<>();
            inputKey = dataSource.next();

            val = dataSource.nextDouble();
            valueMap.add(val);

            if (categoryMap.get(inputKey) == null)
            {
                categoryMap.put(inputKey, valueMap);
            }
            else
            {
                categoryMap.put(inputKey, valueMap);
            }

            dataSource.nextLine();
        }
    }
    // Exception if no lines detected and shows message
    catch (IllegalArgumentException lineExcpt)
    {
        System.out.println("No lines have been input: " + lineExcpt.getMessage());
    }
    finally
    {
        scn.close();
    }

    return categoryMap;

I'm extremely new to java with only about a month of experience.


Solution

  • This is the logic inside your while loop needs some modification. Currently you are overriding the value list with a new one each time.

    Here is what you have on paper:

    • If the key does not exist, create a new list with the given double and use it as the value.
    • Else, get the (already existing) list and add the double to it.

    In code, we just need to modify what you did:

    String inputKey = dataSource.next();
    double val = dataSource.nextDouble();
    List<Double> list = categoryMap.get(inputKey);
    
    if (list == null)                    // If the key does not exist
    {
        list  = new ArrayList<>();       // create a new list
        list.add(val);                   // with the given double
        categoryMap.put(inputKey, list); // and use it as the value
    }
    else                                 // Else
    {
        list.add(val)                    // (got the list already) add the double to it
    }