java8写一个将两个list按照复数个key进行match,保留匹配成功的数组的共通方法
时间: 2024-04-29 11:23:05 浏览: 138
java 两个数组合并的几种方法
以下是一个Java 8的示例代码,用于将两个列表按照复数个键进行匹配,并保留匹配成功的共同元素。
```
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class ListMatcher {
public static <T> List<T> match(List<T> list1, List<T> list2, String... keys) {
Map<String, List<T>> map1 = buildMap(list1, keys);
Map<String, List<T>> map2 = buildMap(list2, keys);
return map1.entrySet().stream()
.filter(e -> map2.containsKey(e.getKey()))
.flatMap(e -> matchLists(e.getValue(), map2.get(e.getKey())).stream())
.collect(Collectors.toList());
}
private static <T> Map<String, List<T>> buildMap(List<T> list, String... keys) {
Map<String, List<T>> map = new HashMap<>();
for (T t : list) {
String key = buildKey(t, keys);
if (!map.containsKey(key)) {
map.put(key, new ArrayList<>());
}
map.get(key).add(t);
}
return map;
}
private static <T> String buildKey(T t, String... keys) {
StringBuilder sb = new StringBuilder();
for (String key : keys) {
try {
sb.append(t.getClass().getMethod(key).invoke(t));
} catch (Exception e) {
throw new RuntimeException("Failed to build key for " + t, e);
}
}
return sb.toString();
}
private static <T> List<T> matchLists(List<T> list1, List<T> list2) {
List<T> result = new ArrayList<>();
for (T t : list1) {
if (list2.contains(t)) {
result.add(t);
}
}
return result;
}
}
```
使用示例:
```
public class Test {
public static void main(String[] args) {
List<Person> list1 = new ArrayList<>();
list1.add(new Person("John", "Doe", 20));
list1.add(new Person("Jane", "Doe", 25));
list1.add(new Person("Bob", "Smith", 30));
List<Person> list2 = new ArrayList<>();
list2.add(new Person("John", "Doe", 20));
list2.add(new Person("Mary", "Johnson", 35));
List<Person> result = ListMatcher.match(list1, list2, "getLastName", "getAge");
System.out.println(result);
}
static class Person {
private String firstName;
private String lastName;
private int age;
public Person(String firstName, String lastName, int age) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public int getAge() {
return age;
}
@Override
public String toString() {
return firstName + " " + lastName + " (" + age + ")";
}
}
}
```
上面的示例将两个人员列表按照姓和年龄进行匹配,并返回匹配成功的人员列表。输出结果为:
```
[John Doe (20)]
```
阅读全文