java8写一个按复数个key将两个list进行match的共通方法
时间: 2024-06-12 22:07:28 浏览: 188
以下是一个Java 8的实现,其中使用了流处理和lambda表达式:
public static <T> List<T> matchLists(List<T> list1, List<T> list2, Function<T, Object> keyExtractor) {
Map<Object, Long> map1 = list1.stream().collect(Collectors.groupingBy(keyExtractor, Collectors.counting()));
Map<Object, Long> map2 = list2.stream().collect(Collectors.groupingBy(keyExtractor, Collectors.counting()));
return map1.entrySet().stream()
.filter(e -> map2.containsKey(e.getKey()) && map2.get(e.getKey()).equals(e.getValue()))
.flatMap(e -> list1.stream().filter(t -> keyExtractor.apply(t).equals(e.getKey())))
.collect(Collectors.toList());
}
该方法接受两个列表和一个键提取函数。它首先使用groupingBy
方法将两个列表中的元素按照给定的键提取函数分组,并计算每个组的数量。然后,它将两个列表中的组进行匹配,并返回两个列表中共通的元素。在这个实现中,我们使用了flatMap
方法来展平每个组中的元素,并将它们组合成一个单独的列表。
使用示例:
List<Integer> list1 = Arrays.asList(1, 2, 3, 3, 4, 5);
List<Integer> list2 = Arrays.asList(2, 3, 3, 5, 5, 6);
List<Integer> commonList = matchLists(list1, list2, Function.identity());
System.out.println(commonList); // 输出 [2, 3, 3, 5]
在这个例子中,我们使用了Function.identity()
作为键提取函数,它将列表中的元素作为键。我们可以看到,matchLists
方法成功地找到了两个列表中的共通元素。
相关推荐


















