Home > OS >  I have a HashSet<Prerequisite> pre. Is there a fast way to do HashSet<int> PreIDs = for
I have a HashSet<Prerequisite> pre. Is there a fast way to do HashSet<int> PreIDs = for

Time:12-08

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?

CodePudding user response:

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());
  • Related