为了找到两个列表的交集并按从大到小的顺序返回结果,我们可以使用 Set 来存储两个列表的元素,然后找出它们的交集。最后,我们将交集中的元素排序并返回。以下是完善后的代码:
java
import java.util.*;
public class Main {
public static List<Integer> solution(List<Integer> a, List<Integer> b) {
Set<Integer> setA = new HashSet<>(a);
Set<Integer> setB = new HashSet<>(b);
Set<Integer> intersection = new HashSet<>(setA);
intersection.retainAll(setB); // 保留两个集合的交集
List<Integer> result = new ArrayList<>(intersection);
Collections.sort(result, Collections.reverseOrder()); // 从大到小排序
return result;
}
public static void main(String[] args) {
System.out.println(solution(Arrays.asList(1, 2, 3, 7), Arrays.asList(2, 5, 7)).equals(Arrays.asList(7, 2)));
System.out.println(solution(Arrays.asList(1, 4, 8, 10), Arrays.asList(2, 4, 8, 10)).equals(Arrays.asList(10, 8, 4)));
System.out.println(solution(Arrays.asList(3, 5, 9), Arrays.asList(1, 4, 6)).equals(Collections.emptyList()));
System.out.println(solution(Arrays.asList(1, 2, 3), Arrays.asList(1, 2, 3)).equals(Arrays.asList(3, 2, 1)));
}
}
这段代码首先将两个列表转换为 HashSet,然后使用 retainAll 方法找出两个集合的交集。接着,我们将交集转换为列表,并使用 Collections.sort 方法对其进行降序排序。最后,返回排序后的列表。在 main 方法中,我们使用几个测试用例来验证 solution 方法的正确性。