I have a 2D array arr= [[1,4],[4,4],[2,2],[3,4],[1,1]]
I want to put it in a PriorityQueue in such a way that it is stored in the following order: [[1,1],[2,2],[1,4],[3,4],[4,4]]
i.e
If the first element is same for two arrays then the one with lower value of second element should appear first
If the second element is same for two arrays then the one with lower value of first element should appear first
Else the one with lower value of second element should appear first
I tried the following code :
import java.io.*;
import java.util.*;
class Check2
{
public static void main(String[] args) {
int events[][]={{1,4},{4,4},{2,2},{3,4},{1,1}};
PriorityQueue<int[][]> min_heap= new PriorityQueue<int[][]>(events ,new Comparator<Integer>()
{
@Override
public int compare(int a[][], int b[][])
{
int res=-1;
if(a[0][1]==b[0][1])
{
if(a[0][0]>b[0][0])
res=-1;
else
res=1;
}
else
{
if(a[0][1]>b[0][1])
res=-1;
else
res=1;
}
}
}
);
}
}
I'm getting the following error :
Check2.java:8: error: <anonymous Check2$1> is not abstract and does not override abstract method compare(Integer,Integer) in Comparator
{
^
Check2.java:9: error: method does not override or implement a method from a supertype
@Override
^
Check2.java:7: error: incompatible types: int[][] cannot be converted to int
PriorityQueue<int[][]> min_heap= new PriorityQueue<int[][]>(events ,new Comparator<Integer>()
^
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output
3 errors
I understand that the compare function wont work for 2d arrays here, but how do I achieve the result.
I tried implementing other techniques by checking everywhere but those didn't worked out. Please help.
In line
PriorityQueue<int[][]> min_heap= new PriorityQueue<int[][]>(events ,new Comparator<Integer>()
you provide collection as first argument, but PriorityQueue
doesn't have such constructor. You can't provide comparator and collection in one constructor.
And still you don't need to store int[][]
in PriorityQueue
to solve this, store int[]
instead.
public static void main(String[] args) {
int[][] events ={{1,4},{4,4},{2,2},{3,4},{1,1}};
PriorityQueue<int[]> min_heap = new PriorityQueue<>((x, y) -> {
if(x[0] != y[0]) {
return Integer.compare(x[0], y[0]);
}
if(x[1] != y[1]) {
return Integer.compare(x[1], y[1]);
}
return 0;
});
min_heap.addAll(Arrays.asList(events));
while(min_heap.peek() != null) {
System.out.println(Arrays.toString(min_heap.poll()));
}
}
Output:
[1, 1]
[1, 4]
[2, 2]
[3, 4]
[4, 4]