Java8写一个共通方法,将两个类型不同的stream输入按多个字段进行匹配,并返回匹配成功的两个输出数据。已知stream输入已按匹配字段排好序,使用了迭代器和循环来避免嵌套循环。
时间: 2024-04-30 20:19:23 浏览: 96
Java8 Stream对两个 List 遍历匹配数据的优化处理操作
3星 · 编辑精心推荐
可以使用Java 8的Stream API和Lambda表达式来实现这个共通方法,以下是示例代码:
```java
import java.util.*;
import java.util.stream.*;
public class MatchStreams {
public static <T1, T2, R> List<R> matchStreams(
Stream<T1> stream1, Function<T1, Comparable> key1,
Stream<T2> stream2, Function<T2, Comparable> key2,
BiFunction<T1, T2, R> merger) {
// 将stream1和stream2转化为迭代器
Iterator<T1> iter1 = stream1.iterator();
Iterator<T2> iter2 = stream2.iterator();
// 分别获取stream1和stream2的第一个元素
T1 item1 = iter1.hasNext() ? iter1.next() : null;
T2 item2 = iter2.hasNext() ? iter2.next() : null;
List<R> result = new ArrayList<>();
while (item1 != null && item2 != null) {
Comparable key1Val = key1.apply(item1);
Comparable key2Val = key2.apply(item2);
// 如果key1小于key2,则从stream1中获取下一个元素
if (key1Val.compareTo(key2Val) < 0) {
item1 = iter1.hasNext() ? iter1.next() : null;
continue;
}
// 如果key1大于key2,则从stream2中获取下一个元素
if (key1Val.compareTo(key2Val) > 0) {
item2 = iter2.hasNext() ? iter2.next() : null;
continue;
}
// 如果key1等于key2,则将两个元素合并并添加到结果列表中
result.add(merger.apply(item1, item2));
// 分别获取stream1和stream2的下一个元素
item1 = iter1.hasNext() ? iter1.next() : null;
item2 = iter2.hasNext() ? iter2.next() : null;
}
return result;
}
}
```
使用示例:
```java
import java.util.*;
public class TestMatchStreams {
public static void main(String[] args) {
List<Person> people = Arrays.asList(
new Person("Alice", 25),
new Person("Bob", 30),
new Person("Charlie", 35)
);
List<Job> jobs = Arrays.asList(
new Job("Engineer", 10000),
new Job("Manager", 20000),
new Job("CEO", 50000)
);
List<PersonJobMatch> matches = MatchStreams.matchStreams(
people.stream(), Person::getAge,
jobs.stream(), Job::getSalary,
PersonJobMatch::new);
matches.forEach(System.out::println);
}
}
class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
@Override
public String toString() {
return name + " (" + age + ")";
}
}
class Job {
private String title;
private int salary;
public Job(String title, int salary) {
this.title = title;
this.salary = salary;
}
public String getTitle() {
return title;
}
public int getSalary() {
return salary;
}
@Override
public String toString() {
return title + " (" + salary + ")";
}
}
class PersonJobMatch {
private Person person;
private Job job;
public PersonJobMatch(Person person, Job job) {
this.person = person;
this.job = job;
}
@Override
public String toString() {
return person.getName() + " matched with " + job.getTitle();
}
}
```
输出结果:
```
Bob matched with Manager
Charlie matched with CEO
```
阅读全文