Search code examples
javaguava

Java three attributes, best way to store + sort


I have a datastructure stored in a map with a multimap as values that I want to sort by multiple attributes.

Background: I have a JavaFX GridPane in which I want to display some things in an ordered form. So for each point within the GridPane I have some Elements with one+ String related to them. I want to display the Elements based on the alphabetical order of the Strings.

I have the following for now:

Map<Coordinate, Multimap<Element, String>> myMap = new HashMap<Coordinate, Multimap<Element, String>>();

But for me it is not clear, how to do the sorting. As you see by the usage of Multimap, one Element can have multiple Strings. At the end I want to order by Coordinate (x and y) and by the String attribute for each coordinate. How to do that? Or does anyone have a better idea how to store these attributes?

Edit: Coordinate sorting is easy and not the problem:

List<Coordinate> keys = new ArrayList<Coordinate>(myMap.keySet());
Comparator<Coordinate> comparator = Comparator.comparing(Coordinate::getX).thenComparing(Coordinate::getY);
Collections.sort(keys, comparator);

I have just explained it to make my problem clear. The main problem is: How to sort the strings with related elements for each coordinate. Or a "better" structure to save the attributes.

Thanks!


Solution

  • Oh damn. Can answer this question by myself. I just make the String the key and the Element the value. Then using

    ListMultimap<String, Element> lmm = Multimaps.newListMultimap(
    new TreeMap<>(), ArrayList::new);
    

    as suggested here. Et voilà... For each Coordinate the inner map is sorted by the String attribute.