-2

I have been given the data for different cars(Year, Model) in the form of Car, consider 2 streams of data coming into my system.

Input Data:

("2018", "i20") ("2018", "zen") ("2016", "alto") ("2015", "k10") ("2014", "ertiga") ("2016", "i20")

What i need to achieve is that when user enters a valid key e.g "2018" as a search keyword, he should be displayed all the associated car models in the sorted order for that key.

e.g in this case output for "2018" should be : [i20, zen]

I am aware that in java hashmap can't have duplicate keys and did some research also that this can be implemented using MultiMap but would really appreciate some leads here.

saas1990
  • 35
  • 8
  • What have you tried so far? – Mark Dec 06 '18 at 09:57
  • 1
    "this can be implemented using MultiMap" Yes, it sure can. Use it. – Michael Dec 06 '18 at 09:58
  • It can also be implemented by just creating an `ArrayList` which does allow duplicates. – Mark Dec 06 '18 at 09:59
  • Possible duplicate of [Group a list of objects by an attribute : Java](https://stackoverflow.com/questions/21678430/group-a-list-of-objects-by-an-attribute-java) – LuCio Dec 06 '18 at 10:05
  • Without using any librarys, a HashMap is perfect for this problem. I think if you spend some time learning about how the Map interface works you will come up with a nice solution. – Mark Dec 06 '18 at 10:05

3 Answers3

0

Put the values into a Map<String, List<String>> and get the list using get(String key)

twobiers
  • 1,057
  • 1
  • 11
  • 27
0

Yes, this can be implemented using com.google.common.collect.Multimap. Try below:

Multimap<String, String> cars = ArrayListMultimap.create();
cars.put("2018", "i20");
cars.put("2018", "zen");
cars.put("2016", "alto");
cars.put("2015", "k10");
cars.put("2014", "ertiga");
cars.put("2016", "i10");
System.out.println(cars.get("2018"));

If you don't want to use a 3rd party library, you can go with

Map<String, List<String>>.
Aditya Narayan Dixit
  • 2,105
  • 11
  • 23
0

You can put values in Map<String, Set<TreeSet>> Where TreeSet keeps your value sorted

Naghaveer R
  • 2,890
  • 4
  • 30
  • 52