In my app i have a function that give me that type of data:
a Year(int) and a String associated to that year (years can have associated more string):
2016 - "1A2B3C"
2009 - "8DF56R"
2009 - "8E4I1J"
2013 - "P6F2T8"
2009 - "4K6J5U"
I want create an array of String for each Year, than sort the Years for increasing years. Like this:
2009 - "8DF56R" "8E4I1J" "4K6J5U"
2013 - "P6F2T8"
2016 - "1A2B3C"
The Year should be the index, How can i retrieve that output?
Sorry for the noob question but I tried array of array, ArrayList and Map but i'm probably missing something.
You should use a Map
of List
s like this:
Map<Integer, List<String>> = new TreeMap<>();
and you can fill up the List
s associated with an Integer
key (date). The TreeMap
sorts your keys according to their natural ordering (ascending by default if I recall it right).
You can also create a custom Comparator
if he default is not satisfactory for you
Another solution is create a Class T containing your informations (year, String, etc.) and implementing Comparable interface. Method compareTo(T) will compare years. By this way you can handle more informations. Object of this type can be inserted in SortedSet, for example, or a List used with Collections.sort or with Java8 Stream.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.