【问题标题】:Iterating through the elements of a HashSet containing user defined objects and displaying the elements that meet a certain criteria遍历包含用户定义对象的 HashSet 的元素并显示满足特定条件的元素
【发布时间】:2017-03-11 06:50:17
【问题描述】:
public class AnotherCompany {

    public static void main(String[] args) {
        HashSet<Employee> h = new HashSet<Employee>();
        Employee e0 = new Employee("Mayank","IT",50000,10,10,10);
        Employee e1 = new Employee("Dhruv","IT",50000,10,10,10);
        Employee e2 = new Employee("Mayank","Accounts",50000,10,10,10);
        Employee e3 = new Employee("Mayank","IT",50000,10,10,10);
        h.add(e0);
        h.add(e1);
        h.add(e2);
        h.add(e3);
        e0.display(h,"IT");
    }
}

现在如果我要写一个只显示那些在 IT 部门工作的员工的显示方法,我该怎么办?

【问题讨论】:

  • 你使用的是 java 8 吗?
  • 这是你的作业吗?
  • 是的,我正在使用 java 8
  • 看看foreach loop
  • 是的,这是我的功课!

标签: java for-loop collections iteration java-stream


【解决方案1】:

您可以使用简单的for-loop 迭代来获得结果。假设Employeeprivate String field

Set<Employee> newSet = new HashSet<>();

for (Employee e: h) {
    if (e.getField().equals("IT")) {
        newSet.add(e);
        System.out.println(e.toString());
    }
}

您可以使用Java 8 中的Stream API 获得相同的结果(请参阅these articles 关于它):

Set<Employee> newSet = h.stream()
    .filter(e -> e.field.equals("IT"))
    .collect(Collectors.toCollection(HashSet::new));

您可能希望将它们打印出来,而不是将它们全部添加到新的Set

h.stream()
    .filter(e -> e.field.equals("IT"))
    .forEach(e -> System.out.print(e + "\n"));

还有更好的声明方式:

Set<Employee> h = new HashSet<>();

【讨论】:

  • 即使Employee有一个私有的String字段,它仍然可以被同一个类中的成员方法访问!
  • 你能告诉我更多关于 getField() 方法的信息吗?
  • Argh 你用流答案更快 :-) + 1 对于正确的 Java 8
  • @MayankBhardwaj 我忘记了在流中不需要使用吸气剂。我修复了如果。它本来是一个吸气剂。
  • OP 不是在问如何打印东西,而不是如何创建新的过滤集吗?为什么在第一个示例中有 newSet?
【解决方案2】:
  1. 而不是HashSet&lt;Employee&gt; h = new HashSet&lt;Employee&gt;(); 使用类似的东西 Set&lt;Employee&gt; h = new HashSet&lt;&gt;();

  2. 内部display方法使用

    for (Employee  emp : h) {
      if(emp.getDepartment().equals(department)) {
        System.out.println("Employee found");
      }
    }
    

注意:使用 jdk 8,您可以尝试使用函数式循环。

【讨论】:

    【解决方案3】:
    public void display(HashSet<Employee> h,String dept) {
        for(Employee e : h) {
            if(e.dept.equals(dept)) {
                System.out.println(e);
            }
        }    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-28
      • 2013-03-21
      相关资源
      最近更新 更多