假设有两个列表:
列表 listA = Arrays.asList(1,2,3,4,5,6,7,6,5,4,3,2,1,0); 该列表是用于对另一个列表B进行排序的模板。
List listB = Arrays.asList(0,106,107,101,105,102,102,103,104,106,105,103,101,104); 另一方面,这个列表是未排序的。
最终列表可以说 listC 的顺序应该是 (101,102,103,104,106,107,106,105,104,103,102,101,0)?我正在使用比较器,但对于不同的用例它会失败?
公共类JavaComparator { 公共静态无效主(字符串[] args){
List<Integer> listA = Arrays.asList(1,2,3,4,5,6,7,6,5,4,3,2,1,0);
List<Integer> listB = Arrays.asList(0,106,107,101,105,102,102,103,104,106,105,103,101,104);
System.err.println(listA);
System.err.println(listB);
// Create a set of elements present in listB for faster lookup
Set<Integer> setB = new HashSet<>(listB);
// Sort listA based on the index in listB or use a default index if not present
listB.sort(Comparator.comparingInt(a -> {
int index = listA.indexOf(a);
if (index == -1) {
// If the element is not in listB, check for nearby values
int indexPlusOne = listA.indexOf(a + 100);
int indexMinusOne = listA.indexOf(a - 100);
if (indexPlusOne != -1) {
return indexPlusOne;
} else if (indexMinusOne != -1) {
return indexMinusOne;
} else {
// Use a default index if not present in listB or nearby
return Integer.MAX_VALUE;
}
}
return index;
}));
System.err.println("Rearranged listB: " + listB);
}
}
这是我尝试过的,这是我得到的解决方案
[1, 2, 3, 4, 5, 6, 7, 6, 5, 4, 3, 2, 1, 0] [0、106、107、101、105、102、102、103、104、106、105、103、101、104] 重新排列的列表B:[101, 101, 102, 102, 103, 103, 104, 104, 105, 105, 106, 106, 107, 0] - 错误的解决方案!
我想,这段代码可能对你有帮助
public class Main {
public static void main(String[] args) {
List<Integer> listA = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 6, 5, 4, 3, 2, 1, 0);
List<Integer> listB = Arrays.asList(0,106,107,101,105,102,102,103,104,106,105,103,101,104);
// ensure, that sizes are equal
assert (listA.size() == listB.size());
// sort for better mapping
List<Integer> listAValues = listA.stream().sorted().toList();
List<Integer> listBValues = listB.stream().sorted().toList();
// map to ensure, that template completes
Map<Integer, Integer> template = new HashMap<>();
Set<Integer> processedB = new HashSet<>();
for (int i = 0; i < listAValues.size(); i++) {
Integer key = listAValues.get(i);
Integer value = listBValues.get(i);
if (template.containsKey(key)) {
assert(template.get(key).equals(value));
} else {
assert(!processedB.contains(value));
template.put(key, value);
processedB.add(value);
}
}
// rearrange
List<Integer> rearrangedListB = listA
.stream()
.map(template::get)
.toList();
System.err.println("Rearranged listB: " + rearrangedListB);
}
}
我将值从 A 映射到 B + 确保每个值都有正确的数字。完成此操作后,我重新排列列表 B。
这是为我打印的代码
Rearranged listB: [101, 102, 103, 104, 105, 106, 107, 106, 105, 104, 103, 102, 101, 0]