Q:

Iterating through the elements of a HashSet containing user defined objects and displaying the elements that meet a certain criteria

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");
    }
}

Now if I have to write a display method which displays only those employees that work in the IT department,What do I do?

A:

You can use a simple for-loop iteration to get the results. Let's assume Employee has private String field.
Set<Employee> newSet = new HashSet<>();

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

You can achieve the same result using Stream API from Java 8 (see these articles about it):
Set<Employee> newSet = h.stream()
    .filter(e -> e.field.equals("IT"))
    .collect(Collectors.toCollection(HashSet::new));

You may want to print them out instead of adding all of them in a new Set:
h.stream()
    .filter(e -> e.field.equals("IT"))
    .forEach(e -> System.out.print(e + "\n"));

There's also the better way of declaration:
Set<Employee> h = new HashSet<>();

