0

I've created a new class. It's a map. I need to create a method within the same class for populating it with some test data. No user input required, simply all done in this code. Just a few examples like "Steve" and his interests like "hiking" "golf" but the interests need to be in a list.

The part that's confusing me is populating the list part of the map, i'm not sure how to. interests.put() doesn't seem to work. Can anybody help?

public class Singles
{
   // instance variables - replace the example below with your own
   private Map<String, List<String>> interests;

   /**
    * Constructor for objects of class Singles
    */
   public Singles()
   {
      // initialise instance variables
      super();
      this.interests = new HashMap<>();
   }

  public void popInterests()
  {
     //code to go here. CONFUSED
  }
}

1 Answers1

2

You can create an object of List and insert into the map.

 import java.util.*;
    public class Singles
    {
      public static void main(String[] args)
      {
           Map<String, List<String>> interests= new HashMap<>();
           List<String> hobby = new ArrayList<String>();
           hobby.add("swimming");
           hobby.add("dancing");
           interests.put("Steve",hobby);

      }
}

If you want the list of hobbies to be un modifiable, use List.of.

Map<String, List<String>> interests= new HashMap<>();
interests.put("Steve",List.of("swimming","dancing"));
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
Shubham Chopra
  • 1,678
  • 17
  • 30
  • Thank you! the method header is to not take any kind of argument though. Does that change anything? – craiggantry May 07 '19 at 09:12
  • @craiggantry The `main` method is special in Java, and always takes an argument of an array of strings. That argument is irrelevant to the point of the code shown here. – Basil Bourque May 07 '19 at 09:15