Search code examples
javaarraylistcollectionshashmap

In HashMap I get the whole list, when I try to retrieve value pairs related to the key


In this program when I run map.get("b"), I get the whole list but I want only value pair which is related to key "b".

    package test1;
    import java.util.*;
    public class Test1 {
    
        public static void main(String[] args) {
            Scanner in = new Scanner(System.in);//scanner object
            Map<String, List<Integer>> map = new HashMap<String, List<Integer>>();//map
            List<Integer> times = new ArrayList<Integer>();//arraylist
            
            int exit = 0;
            int stime;
            int etime;
            String [] letters = {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
                "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"};
            for(int x = 0; exit == 0 ; x++){
                    System.out.println("Enter 1 -> ");
                    stime = in.nextInt();
                    System.out.println("Enter 2 --> ");
                    etime = in.nextInt();
                    if(stime == -1 || etime == -1){
                        exit = -1;
                    }
                    times.add(stime);
                    times.add(etime);
                    map.put(letters[x],times);
           }

            System.out.println(map.get("b"));
            
        }
}

Solution

  • The issue is that the Arraylist times is initialized outside the for loop. Below should work.

       for(int x = 0; exit == 0 ; x++){
                System.out.println("Enter 1 -> ");
                stime = in.nextInt();
                System.out.println("Enter 2 --> ");
                etime = in.nextInt();
                if(stime == -1 || etime == -1){
                    exit = -1;
                }
                List<Integer> times = new ArrayList<Integer>();//arraylist
                times.add(stime);
                times.add(etime);
                map.put(letters[x],times);
       }
    

    Below uses Pair data structure from Apache Commons Lang library:

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);//scanner object
        Map<String, Pair> map = new HashMap<>();//map
    
    
        int exit = 0;
        int stime;
        int etime;
        String [] letters = {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
            "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"};
        for(int x = 0; exit == 0 ; x++){
                System.out.println("Enter 1 -> ");
                stime = in.nextInt();
                System.out.println("Enter 2 --> ");
                etime = in.nextInt();
                if(stime == -1 || etime == -1){
                    exit = -1;
                }
                map.put(letters[x],Pair.of(stime, etime));
       }
    
        System.out.println(map.get("b"));
    }