user1950055
user1950055

Reputation: 157

Sorting an ArrayList of Int[] on multiple indexes

I currently have an ArrayList of int[]. The int[] has 5 elements. I want to be able to sort this ArrayList on the basis of the 2nd and 4th indexes of the my int[]. How do I do this in Java?

Upvotes: 0

Views: 135

Answers (2)

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 135992

You need a custom Comparator like this

    class IntArrayComparator implements Comparator<int[]> {
        private final int[] ai;

        IntArrayComparator(int[] ai) {
            this.ai = ai;
        }

        @Override
        public int compare(int[] a1, int[] a2) {
            for (int i : ai) {
                int c = Integer.compare(a1[i], a2[i]);
                if (c != 0) {
                    return c;
                }
            }
            return 0;
        }
    }

note that Integer.compare(int, int) is added in Java 7, in earlier versions use

int c = (a1[i] < a2[i]) ? -1 : a1[i] == a2[i] ? 0 : 1;

Upvotes: 0

Daniel Kaplan
Daniel Kaplan

Reputation: 67310

package com.sandbox;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class Sandbox {

    public static void main(String[] args) {
        List<int[]> list = new ArrayList<int[]>();
        list.add(new int[]{1, 4, 6, 8, 9});
        list.add(new int[]{1,3,6,7,8});
        list.add(new int[]{1,4,6,7,9});
        Collections.sort(list, new Comparator<int[]>() {
            public int compare(int[] o1, int[] o2) {
                int compare = Integer.compare(o1[1], o2[1]);
                //if they're equal on this element then compare the next element
                return compare == 0 ? Integer.compare(o1[3], o2[3]) : compare;
            }
        });
        for (int[] ints : list) {
            System.out.println(Arrays.toString(ints));
        }
    }
}

This is the output:

[1, 3, 6, 7, 8] [1, 4, 6, 7, 9] [1, 4, 6, 8, 9]

Upvotes: 2

Related Questions