Java - 根据另一个数组的值对一个数组进行排序?
问题描述:
我有一个字符串数组,它是来自外部代码的类的实例,我宁愿不改变。
I have an array of Strings that are instances of a class from external code that I would rather not change.
我还有一个生成的int数组通过调用每个对象上的函数。所以我有
I also have an array of ints that was generated by calling a function on each object. So I have
A: [string1,string2,string3]
和
B: [40,32,34]
如何轻松地对A进行排序,使其按B的值排序。我有可用的提升。我想按顺序对A进行排序:
How do I easily sort A such that it is sorted in by the values of B. I have boost available. I want to sort A such that it is in the order:
[string2, string3, string1]
在javascript中你可以这样做:
In javascript you could do this like:
B.sort(function(a,b){return A[B.indexOf(a)] < A[B.indexOf(b)];});
答
我使用Comparator接口解决了这个问题。
I solved this problem by using Comparator interface.
import java.util.Comparator;
import java.util.Collections;
import java.util.List;
import java.util.Arrays;
public class ComparatorDemo {
public static void main(String[] args) {
List<Area> metaData = Arrays.asList(
new Area("Joe", 24),
new Area("Pete", 18),
new Area("Chris", 21),
new Area("Rose",21)
);
Collections.sort(metaData, new ResultComparator());
for(int i =0 ;metaData.size()>i;i++)
System.out.println(metaData.get(i).output);
}
}
class ResultComparator implements Comparator<Area> {
@Override
public int compare(Area a, Area b) {
return a.result < b.result ? -1 : a.result == b.result ? 0 : 1;
}
}
class Area{
String output;
int result;
Area(String n, int a) {
output = n;
result = a;
}
}