从您的示例中,您似乎想要匹配两个数组之间的排名顺序。如果我在这里错了,请告诉我,但要进一步分解您的示例:
// Ranking order here is [4, 0, 1, 2, 3]
int[] first = {8,1,2,2,3};
int[] second = {0,1,1,3,4};
// If we apply the same ranking order to second we get the following
// {4, 0, 1, 1, 3}
假设这是您想要的,类似以下的内容会起作用。我不知道这样做的简单库方法。
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;
public final class RankOrdering {
public static List<Integer> applyRankOrdering(List<Integer> source, List<Integer> target) {
if (source.size() != target.size()) {
throw new IllegalArgumentException("source and target must be the same size");
}
// Generate the ranking order for the source list: [3, 5, 1, 0, 0] -> [3, 4, 2, 1, 0]
var sourceSorted = source.stream().sorted().collect(Collectors.toList());
var sourceValuesToRank = new HashMap<Integer, Integer>();
for (int i = 0; i < sourceSorted.size(); i++) {
sourceValuesToRank.put(sourceSorted.get(i), i);
}
var sourceRankOrder = source
.stream()
.map(sourceValuesToRank::get)
.collect(Collectors.toList());
// Determine which rank each element of target has
var targetSorted = target.stream().sorted().collect(Collectors.toList());
var targetRankToValue = new HashMap<Integer, Integer>();
for (int i = 0; i < targetSorted.size(); i++) {
targetRankToValue.put(i, targetSorted.get(i));
}
// Apply source ranking order to the values from target
return sourceRankOrder
.stream()
.map(targetRankToValue::get)
.collect(Collectors.toList());
}
public static void main(String[] args) {
var source = List.of(8, 1, 2, 2, 3);
var target = List.of(0, 1, 1, 3, 4);
System.out.println(applyRankOrdering(source, target));
}
}
哪些打印:
[4, 0, 1, 1, 3]