Java – How to process this type of data into Array – JAVA

How to process this type of data into Array – JAVA… here is a solution to the problem.

How to process this type of data into Array – JAVA

In my application I have a function that can provide this type of data :

A Year(int) and a string associated with that year (a year can be associated with more strings):

2016 – “1A2B3C”

2009 – “8DF56R”

2009 – “8E4I1J”

2013 – “P6F2T8”

2009 – “4K6J5U”

I want to create an array of strings for each year instead of sorting the years by increasing ones. Like this:

2009 – “8DF56R” “8E4I1J” “4K6J5U”

2013 – “P6F2T8”

2016 – “1A2B3C”

Year should be index,
How do I retrieve that output?

Sorry for this rookie issue, but I tried arrays of arrays, ArrayList, and Map, but I may have missed something.

Solution

You should use Map: for List like this

Map<Integer, List<String>> = new TreeMap<>();

And you can fill in the List associated with the Integer key (date). TreeMap sorts keys according to their natural order (ascending by default, if I’m not mistaken).

If his default value is not satisfactory to you, you can also create a custom Comparator

Related Problems and Solutions