gpt4 book ai didi

java - 如何以有效的方式与基于键的对象数组列表进行比较

转载 作者:行者123 更新时间:2023-12-04 14:52:54 26 4
gpt4 key购买 nike

如何以高效的方式与基于键的对象数组列表进行比较。

我有一组对象 personDetails 和 departmentDetails。

在这里,我试图根据名为 deptCode 的属性找出两个对象之间的区别。

这是我正在尝试的。

package com.education;

import java.util.*;
import java.util.stream.Collectors;

public class educationMain {

public static void main(String[] args) {

List<person> list=new ArrayList<person>();
person l1 = new person(1,"Samual",100,"Sales","Business");
person l2 = new person(2,"Alex",100,"Sales","Business");
person l3 = new person(3,"Bob",101,"Engineering","Technology");
person l4 = new person(4,"Michel",101,"Engineering","Technology");
person l5 = new person(5,"Ryan",102,"PR","Services");
person l6 = new person(6,"Horward",103,"Leadership","Managmnet");
person l7 = new person(7,"Cyna",104,"HR","Human Resource");
list.add(l1);
list.add(l2);
list.add(l3);
list.add(l4);
list.add(l5);
list.add(l6);
list.add(l7);



List<department> depList = new ArrayList<department>();


department d1 = new department(100, "Sales","Business");
department d2 = new department(101, "Engineering","Technology");
department d3 = new department(102, "PR","Services");
depList.add(d1);
depList.add(d2);
depList.add(d3);

List<person> listC = new ArrayList<person>();


for(person p : list) {
boolean flag = false;
for (department d:depList) {
if(p.deptCode == d.deptCode) {
flag = false;
break;
}else {
flag = true;
}
}
if(flag == true) {
listC.add(p);
}
}

for(person b:listC){
System.out.println(b.personId+" "+b.name+" "+b.deptCode+" "+b.parentDept+" "+b.deptName);
}
}

}

现在打印我想要的东西。但我正在使用两个 for 循环。谁能帮我优化我的代码,因为我在这里使用了两个循环。我想尝试根据一些过滤掉增量的代码。

在 Collection 中,我看到 set 可以,但不能这样写。佳能帮助我优化效率。

输出:

6 Horward 103 Leadership Managmnet

7 Cyna 104 HR Human Resource

最佳答案

roookeee已经给出了很好的答案。我的方法大致相同,这是我的实现:

将所有部门添加到列表后,遍历部门,将代码添加到 HashSet。我不确定类方法到底是什么,但是,假设它们遵循 JavaBean 约定,它可能看起来像这样:

//Create an instance of HashSet
HashSet<Integer> codeSet = new HashSet<>();

//Iterate over the departments and add the department code to a set.
depList.forEach(dept->{
codeSet.add(dept.getDeptCode());
});


List<person> listC = new ArrayList<>();

list.forEach(p->{
if(!codeSet.contains(p.getDeptCode())){
listC.add(p);
}
});

/**
*This reads logically as, "For each person, if the set of department codes
*DOES NOT contain this persons department code, add them to the list".
*/

请原谅任何糟糕的代码格式,我有一段时间没有说 Java,因为我一直在努力学习 Python。另外,我没有专业的编程经验,我只是一些认为编码很整洁的青少年,所以,不要把我的话当作福音。

关于java - 如何以有效的方式与基于键的对象数组列表进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68760141/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com