java8写一个将List<A>与List<B>中多个字段的值进行匹配,匹配一致的List<A>与List<B>分别出力
时间: 2024-04-29 12:24:08 浏览: 108
java使用list实现数据库的like功能
假设List<A>中有属性a1、a2,List<B>中有属性b1、b2,要匹配a1与b1以及a2与b2是否一致,若一致则将相应的List<A>与List<B>分别输出。
代码如下:
```
import java.util.ArrayList;
import java.util.List;
public class MatchList {
public static void main(String[] args) {
List<A> aList = new ArrayList<>();
aList.add(new A("a1", 1));
aList.add(new A("a2", 2));
aList.add(new A("a3", 3));
List<B> bList = new ArrayList<>();
bList.add(new B("b2", 2));
bList.add(new B("b1", 1));
bList.add(new B("b4", 4));
List<A> matchedAList = new ArrayList<>();
List<B> matchedBList = new ArrayList<>();
for (A a : aList) {
for (B b : bList) {
if (a.getA1().equals(b.getB1()) && a.getA2() == b.getB2()) {
matchedAList.add(a);
matchedBList.add(b);
}
}
}
System.out.println("Matched List A:");
for (A a : matchedAList) {
System.out.println(a);
}
System.out.println("Matched List B:");
for (B b : matchedBList) {
System.out.println(b);
}
}
}
class A {
private String a1;
private int a2;
public A(String a1, int a2) {
this.a1 = a1;
this.a2 = a2;
}
public String getA1() {
return a1;
}
public int getA2() {
return a2;
}
@Override
public String toString() {
return "A{" +
"a1='" + a1 + '\'' +
", a2=" + a2 +
'}';
}
}
class B {
private String b1;
private int b2;
public B(String b1, int b2) {
this.b1 = b1;
this.b2 = b2;
}
public String getB1() {
return b1;
}
public int getB2() {
return b2;
}
@Override
public String toString() {
return "B{" +
"b1='" + b1 + '\'' +
", b2=" + b2 +
'}';
}
}
```
注:以上代码仅作为示例,实际开发中需要根据具体情况进行修改。
阅读全文