Baker1562 Baker1562 - 1 month ago 6
Java Question

Treemap with 3 Strings arguments java

I need to save 3 variables in any structure data in java, I was think in treemap because a I need sort the map alphabetically, but, the treemap only take 2 arguments.

Any other structure when a can sort the structure in funtion of first argument? like

["abc","house","car"]
["bdc","house2","car2"]

Answer

You can use a list of arrays with a custom comparator:

public static void main(String[] args) {

    List<String[]> data = new ArrayList<>();
    data.add(new String[]{"bdc", "house2", "car2"});
    data.add(new String[]{"abc", "house", "car"});

    printData(data);

    Collections.sort(data, new Comparator<String[]>() {

        @Override
        public int compare(String[] o1, String[] o2) {
            return o1[0].compareTo(o2[0]);
        }
    });

    System.out.println();
    printData(data);

}

public static void printData(List<String[]> data){
    for(String[] s: data){
        System.out.println(Arrays.toString(s));
    }
}

Output:
Before sorting:
[bdc, house2, car2]
[abc, house, car]

After sorting:
[abc, house, car]
[bdc, house2, car2]

Comments