假如我已经得出两个表的List对象,用java如何关联两个表取出取出id相等的对象并存入List中
时间: 2024-02-26 15:58:55 浏览: 15
假设你有两个表的List对象,每个表中都有一个id属性,你可以使用Java 8的Stream API来实现关联两个表并取出id相等的对象,代码示例如下:
```java
List<Table1> table1List = ...; // 第一个表的List对象
List<Table2> table2List = ...; // 第二个表的List对象
List<Result> resultList = table1List.stream()
.flatMap(table1 -> table2List.stream()
.filter(table2 -> table1.getId() == table2.getId())
.map(table2 -> new Result(table1, table2)))
.collect(Collectors.toList());
```
其中,Result是一个自定义类,用于存储关联后的对象。上述代码中,首先对第一个表的List对象进行遍历,然后对第二个表的List对象进行过滤,只取出id相等的对象,并将两个对象封装成一个Result对象,最后将所有的Result对象收集到一个List中返回。
相关问题
不相等的存入list,相等的存入子list
可以使用一个字典来实现这个功能,遍历列表,如果元素不在字典的键中,就将其作为键加入字典,并将其值初始化为一个列表,将该元素存入该列表。如果元素已经在字典的键中,就将其添加到对应的列表中。最后,将字典中所有值为单个元素的列表转换为非嵌套列表即可。
代码示例:
```
def split_list(lst):
d = {}
for item in lst:
if item not in d:
d[item] = [item]
else:
d[item].append(item)
return [v if len(v) > 1 else v[0] for v in d.values()]
# 测试
lst = [1, 2, 3, 2, 4, 5, 4, 6, 7, 7]
result = split_list(lst)
print(result)
# 输出:[[2, 2], [4, 4], [7, 7], 1, 3, 5, 6]
```
用C语言实现:已知两个链表A和B分别表示两个集合,其元素递增排列。请设计算法求出A与B的交集,并存放于A链表中。
算法思路:
1. 初始化两个指针p和q分别指向链表A和B的头结点;
2. 循环遍历链表A和B,比较p和q指向结点的值,若相等则将该值存入链表A中,并将p和q都往后移一位;
3. 若p指向结点值小于q指向结点值,则将p往后移一位;
4. 若p指向结点值大于q指向结点值,则将q往后移一位;
5. 循环结束条件为p或q指向结点为空。
代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int value;
struct Node* next;
} Node;
Node* createNode(int value) {
Node* node = (Node*) malloc(sizeof(Node));
node->value = value;
node->next = NULL;
return node;
}
void addNode(Node** head, Node** tail, int value) {
Node* node = createNode(value);
if (*head == NULL) {
*head = *tail = node;
} else {
(*tail)->next = node;
*tail = node;
}
}
void printList(Node* head) {
Node* p = head;
while (p != NULL) {
printf("%d ", p->value);
p = p->next;
}
printf("\n");
}
void intersect(Node** A, Node* B) {
Node dummy, *tail = &dummy;
while (*A && B) {
if ((*A)->value < B->value) {
*A = (*A)->next;
} else if ((*A)->value > B->value) {
B = B->next;
} else {
tail->next = *A;
tail = *A;
*A = (*A)->next;
B = B->next;
}
}
tail->next = NULL;
}
int main() {
Node *A = NULL, *B = NULL;
Node *tail1, *tail2;
addNode(&A, &tail1, 1);
addNode(&A, &tail1, 3);
addNode(&A, &tail1, 5);
addNode(&A, &tail1, 7);
addNode(&B, &tail2, 2);
addNode(&B, &tail2, 4);
addNode(&B, &tail2, 5);
addNode(&B, &tail2, 8);
printf("A: ");
printList(A);
printf("B: ");
printList(B);
intersect(&A, B);
printf("A intersect B: ");
printList(A);
return 0;
}
```
运行结果:
```
A: 1 3 5 7
B: 2 4 5 8
A intersect B: 5
```