RKR
RKR

Reputation: 687

How to keep data in a hash map

I am able to print the the data like below:

id    comes_in
___   ________
1       1
2       1
3       1
4       2
5       2
6       3

where both id and comes_in are integers.Now I want to keep this in a hashmap where key is the comes_in and values are an arraylist of ids.

HashMap<Integer,ArrayList<Integer>> map=new  HashMap<Integer,ArrayList<Integer>>();

So it will be like below:

comes_in     id
________     ___
1             1,2,3 
2             4,5
3             6

But the problem is how to put them in a hashmap because Initially I am unable to group the id by comes_in.Any help is appreciated.

Upvotes: 0

Views: 54

Answers (1)

choasia
choasia

Reputation: 10852

Use Java 8 Stream. Your quest could be achieved easily. See: https://docs.oracle.com/javase/8/docs/api/java/util/stream/Collectors.html#groupingBy-java.util.function.Function-java.util.function.Supplier-java.util.stream.Collector-

public class TestProgram {
  public static void main(String...args) {
    Map<Integer, Integer> map = new HashMap<>();
    map.put(1, 1);
    map.put(2, 1);
    map.put(3, 1);
    map.put(4, 2);
    map.put(5, 2);
    map.put(6, 3);

    Map<Object, List<Object>> result = map.entrySet().stream()
        .collect(Collectors.groupingBy(
              Entry::getValue, 
              HashMap::new, 
              Collectors.mapping(Entry::getKey, Collectors.toList())
            ));
    System.out.println(result);
    // {1=[1, 2, 3], 2=[4, 5], 3=[6]}
  }
}

Upvotes: 1

Related Questions