java - How to sort an array wrt to another one -
what java program perform below task?
given 2 arrays called a
, c
. need sort a
respect c
.
for example, if a={2,3,4}
, c={-1,2,1}
. sorting regards c produce {2,4,3}
i did in c++ using pair<>
. how do same in java using inbuilt features?
you can same in java:
class pair<a, c extends comparable<c>> implements comparable<pair<a,c>> { public final a; public final c c; pair(a a, c c) { this.a = a; this.c = c; } @override public int compareto(pair<a, c> o) { return c.compareto(o.c); } }
...
public static void main(string[] args) { list<pair<integer,integer>> list = new arraylist<>(); list.add(new pair<>(2,-1)); list.add(new pair<>(3,2)); list.add(new pair<>(4,1)); collections.sort(list); list.stream().foreach((pair) -> { system.out.println(pair.a + " " + pair.c); }); }
update:
or, more simply:
class pair<a, c> { public final a; public final c c; pair(a a, c c) { this.a = a; this.c = c; } } public static void main(string[] args) { list<pair<integer,integer>> list = new arraylist<>(); list.add(new pair<>(2,-1)); list.add(new pair<>(3,2)); list.add(new pair<>(4,1)); collections.sort(list, (pair<integer, integer> o1, pair<integer, integer> o2) -> o1.c.compareto(o2.c)); list.stream().foreach((pair) -> { system.out.println(pair.a + " " + pair.c); }); }
Comments
Post a Comment