如果有唯一值,我可以相对于另一个对数组进行排序。但是由于我正在尝试对下面的给定数组进行排序:
initial fuel[]={1,9,9,2,9,9};
initial cost[]={2,6,5,4,3,1};
我想对燃料阵列进行分类,然后再想对燃料阵列分类成本阵列。
我想要如下所示的输出:
final fuel[]={1,2,9,9,9,9};
final cost[]={2,4,6,5,3,1};
下面是我的代码:
public static void sort(List<Integer> c, List<Integer> f) {
List<Integer> cc = new ArrayList<>(c);
Collections.sort(c);
List<Integer> al = new ArrayList<>();
int i = 0;
while (i < c.size()) {
int temp = c.get(i);
int index = cc.indexOf(temp);
al.add(f.get(index));
cc.remove(index);
f.remove(index);
i++;
}
for (int value : c)
System.out.print(value + " ");
System.out.println();
for (int value : al)
System.out.print(value + " ");
}
如何使用比较器以这种方式排序?另外如何使用流api相同?
如果你始终希望将给定的燃料值与成本相关联,那么我建议你创建一个类来保存它们。这将允许正确排序,同时将两个值保持在一起。
int[] fuel = { 1, 9, 9, 2, 9, 9 };
int[] cost = { 2, 6, 5, 4, 3, 1 };
这将创建类,并根据燃料值对它进行排序,然后将其放入列表中。
List<FuelInfo> fuelInfo =
// generate array indices
IntStream.range(0, fuel.length)
// create the objects
.mapToObj(i -> new FuelInfo(fuel[i], cost[i]))
// sort them based on fuel value
.sorted(Comparator.comparing(FuelInfo::getFuel))
// put them in a list.
.collect(Collectors.toList());
fuelInfo.forEach(System.out::println)
印刷
[1, 2]
[2, 4]
[9, 6]
[9, 5]
[9, 3]
[9, 1]
你可以按照以下步骤将各个值复制回列表:
List<Integer> fuelList = fuelInfo.stream()
.map(FuelInfo::getFuel).collect(Collectors.toList());
List<Integer> costList = fuelInfo.stream()
.map(FuelInfo::getCost).collect(Collectors.toList());
如果你要保留重复的默认顺序,那么这将起作用,因为Java中的排序是稳定的(比较等于值时将保持插入顺序)。通过根据燃料阵列的值对索引进行排序,然后使用排序后的索引以正确排序的顺序构建成本列表,可以实现此目的。
Comparator<Integer> comp = (a,b)->Integer.compare(fuel[a],fuel[b]);
Comparator<Integer> comp =
(a, b) -> Integer.compare(fuel[a], fuel[b]);
List<Integer> sortedFuel = Arrays.stream(fuel).sorted()
.boxed().collect(Collectors.toList());
List<Integer> sortedCost = IntStream.range(0, fuel.length)
.boxed().sorted(comp).map(a -> cost[a])
.collect(Collectors.toList());
System.out.println(sortedFuel);
System.out.println(sortedCost);
印刷
[1, 2, 9, 9, 9, 9]
[2, 4, 6, 5, 3, 1]
FuelInfo类
class FuelInfo{
private int fuelAmt;
private int cost;
public FuelInfo(int fuel, int cost) {
this.fuelAmt = fuel;
this.cost = cost;
}
public int getFuel() {
return fuelAmt;
}
public int getCost() {
return cost;
}
public String toString() {
return String.format("[%s, %s]", fuelAmt, cost);
}
}
谢谢你。有没有一种方法可以在不创建新类的情况下做到这一点。我想将两个数组都保留在单独的arrayList中。希望你能回答我的问题。
如果要在分类后保持燃油值和成本之间的严格关联,则不可以。但是请参阅我修改后的解决方案,轻松将其复制回去。到单个列表。
@KhushtarHussain我希望回答你所希望的(希望如此)
我切换到列表以符合您的编辑要求。