-1

My aim is to fill a TreeMap with keys as Integer values, and values as a set of elements from a list. For example say I have a list like:

1 big 345,
1 small 223,
2 big 312,
1 small 116

I'd like the keys of the TreeMap to be the first number, and the values to be sets of the elements in the list. So the map would look like:

1(K)
1 big 345(V)
1 small 223(V)
1 small 116(V)

2(K)
2 big 312(V)

I'm not sure how to implement this, the only code I have written is just to define a tree map and to copy the list into a set. I don't know how I would associate the key to value. Any help is appreciated and will add more info if I am unclear.

Sean2148
  • 365
  • 1
  • 3
  • 13

1 Answers1

1

Supposing your List contains Foo instances and the int value is represented by an id field, you could get as result a TreeMap<Integer, Set<Foo>> object with :

List<Foo> foos = ...
TreeMap<Integer, Set<Foo>>` map = new TreeMap<>();
for (Foo foo : foos){
   map.computeIfAbsent(foo.getId() k-> new HashSet<>())
      .add(foo);
}
davidxxx
  • 125,838
  • 23
  • 214
  • 215