简体   繁体   中英

Can this Java code be made more efficient

I have Java code that applies a function to every element of a HashSet. Each element has to be (1) removed from the HashSet,(2)processed, which returns a result of the same type (and sometimes even the same object instance), and sometimes multiple instances of this type in a collection; (3)the result is replaced in a HashSet.

I delete each element from the original HashSet, processing it's elements until its empty. I place each new instance returned by processing the object in a new HashSet. When I'm done I discard the old HashSet and continue with the new one. I thought I had to do this because otherwise, I risk an infinite loop as I iterate over every element of HashSet while also adding elements to it. The code kinda looks like this. Fct addToHashSet adds 1 or more elements to newSet.

        newSet= new HashSet< myObjectType >(); 
        for (myObjectType s : origSet){
            addToHashSet(newSet, process(s,message)); 
        }
        return newSet;

My questions are:

1) Am I being inefficient by constantly creating and deleting HashSets (this processing is called a lot)?

2) If so, is there a better, in place, manner to process every element once, (I don,t want to process elements that I just added) without creating a new HashSet?

3) If the answer is no, can it be dome for cases where each element of the Hashset is replaced with a single instance? That code looks like that:

        newSet= new HashSet< myObjectType >(); 
        for (myObjectType s : origSet){
            newSet .add(process(s,message)); 
        }
        return newSet;

If you really need the properties of a Set , and if your process returns new instances, as opposed to modifying the instances in the set, then your current solution is fine.

If the process modifies the instances instead of returning new instances, then you can use the forEach method instead:

origSet.forEach(item -> process(item));

If you don't need the properties of a Set , then you could use a Queue<> instead:

int size = queue.size();
for (int i = 0; i < size; i++) {
    queue.add(process(queue.poll()));
}

At the end of this loop, the original elements of the queue will be all gone, it will contain the new elements returned by process .

And if you really need a new set replacing the old one, then you can use a more idiomatic solution with streams (as @Simon pointed out in a comment):

newSet = origSet.stream().map(s -> process(s, message)).collect(Collectors.toSet());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM