Skip to content
Advertisement

I have a HashSet pre. Is there a fast way to do HashSet PreIDs = for each x do x.getID in Pre? (in Java)

There is a class Prerequisite, it has a method getID().

Instead of doing

HashSet<int> PreIDs = new HashSet<>();

for(Prerequisite p: pre// HashSet of Prerequisites)
{
   PreIDs.add(p.getID())
}

is there a more efficient or more concise way to call a method over a HashSet?

Advertisement

Answer

As @ernest_k said, there isn’t any more efficient way in my opinion too. But we can write that whole logic in one line as below (if you are using Java 8 or above) using streams:

Set<Integer> PreIDs = pre.stream()
    .map(Prerequisite::getID)
    .collect(Collectors.toSet());
Advertisement