Maintain an ArrayList of unique arrays in java

Dinero :

How can I maintain an ArrayList of unique arrays?

For instance, if I have the following arrays:

int [] a = {1,2,3};
int [] b = {2,1,3};
int [] c = {2,1,3};

According to my logic I am considering unique combinations. So in the case above a = b = c because they all contain "1", "2", "3".

Ideally I am wondering if there is a data structure in Java that recognizes this.

I tried the following:

Set<int []> result = new LinkedHashSet<>();
int [] x = {1,2,3};
int [] z = {2,1,3};
int [] m = {2,1,3};

result.add(x);
result.add(z);
result.add(m);

for(int [] arr: result){
    printArray(arr);
}

My output was:

1 2 3
2 1 3
2 1 3

Ideally I would want my output to only print one of the combinations above.

YCF_L :

You can create a method to add if not equals like so :

public static Set<int[]> addIfNotExist(Set<int[]> result, int[] array) {
    Arrays.sort(array);
    boolean check = result.stream()
            .anyMatch(a -> {
                Arrays.sort(a);
                return Arrays.equals(a, array);
            });
    if (check) {
        return result;
    } else {
        result.add(array);
        return result;
    }
}

Then you can call your method like so :

result = addIfNotExist(result, x);
result = addIfNotExist(result, z);
result = addIfNotExist(result, m);

Output

[1, 2, 3]

Or if you use a static Set, you can just use :

static Set<int[]> result = new LinkedHashSet<>();

public static void main(String[] args) {

    int[] x = {1, 2, 3};
    int[] z = {2, 1, 3};
    int[] m = {2, 1, 3};

    addIfNotExist(result, x);
    addIfNotExist(result, z);
    addIfNotExist(result, m);

    for (int[] arr : result) {
        System.out.println(Arrays.toString(arr));
    }
}

public static void addIfNotExist(Set<int[]> result, int[] array) {
    Arrays.sort(array);
    boolean check = result.stream()
            .anyMatch(a -> {
                Arrays.sort(a);
                return Arrays.equals(a, array);
            });
    if (!check) {
        result.add(array);
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=138470&siteId=1