java stream实现inner join
时间: 2023-11-21 15:57:24 浏览: 54
以下是Java Stream实现Inner Join的示例代码:
```java
import java.util.*;
import java.util.stream.*;
public class InnerJoinExample {
public static void main(String[] args) {
// 创建左表
List<Map<String, Object>> leftTable = new ArrayList<>();
Map<String, Object> leftRow1 = new HashMap<>();
leftRow1.put("id", 1);
leftRow1.put("name", "Alice");
leftTable.add(leftRow1);
Map<String, Object> leftRow2 = new HashMap<>();
leftRow2.put("id", 2);
leftRow2.put("name", "Bob");
leftTable.add(leftRow2);
// 创建右表
List<Map<String, Object>> rightTable = new ArrayList<>();
Map<String, Object> rightRow1 = new HashMap<>();
rightRow1.put("id", 1);
rightRow1.put("age", 20);
rightTable.add(rightRow1);
Map<String, Object> rightRow2 = new HashMap<>();
rightRow2.put("id", 3);
rightRow2.put("age", 30);
rightTable.add(rightRow2);
// 定义连接条件
String joinColumnTableLeft = "id";
String joinColumnTableRight = "id";
// 执行内连接
List<Map<String, Object>> result = leftTable.stream()
.flatMap(l -> rightTable.stream()
.filter(r -> Objects.equals(l.get(joinColumnTableLeft), r.get(joinColumnTableRight)))
.map(r -> {
Map<String, Object> row = new HashMap<>();
row.putAll(l);
row.putAll(r);
return row;
}))
.collect(Collectors.toList());
// 输出结果
System.out.println(result);
}
}
```
阅读全文