简体   繁体   中英

filtering entries of HashMap and iterate over values

I have useed a HashMap to implement a graph

HashMap<E,Node<E>> graph=new HashMap<E,Node<E>>()

now I want to filter the head nodes out of it (Node class has a method that shows if this node is head or tail)

public Iterator<Node<E>> heads() {
    HashMap<E, Node<E>> heads=new HashMap<E, Node<E>>();
    for(Entry<E, Node<E>> e:graph.entrySet()){
        if(e.getValue().isHead())
            heads.put(e.getKey(), e.getValue());
    }
    return heads.values().iterator();
}

I wanted to know if it is a good way of implementation or is there a better proper way ?

Don't know in what aspect of "Better" you are looking for. Your way works anyway.

There is another way I prefer, by using Guava's Iterables .

it looks something like:

Iterable<Node<E>> heads 
     = Iterables.filter(graph.values(), 
                        new Predicate<Node<E>> {
                            @Override
                            public boolean apply(Node<E> node) {
                                return node.isHead();
                            }
                       );

Edit: If you are using Java 8, you will already find similar feature without 3rd party lib. Thanks to Lambda, the syntax is even easier. Anyway, the idea is the same.

One straightforward improvement over the algorithm you have posted would be to collect the head elements of the map into a list, rather than reconstructing a HashMap with just the head elements in it:

public Iterator<Node<E>> heads() {
    List<Node<E>> heads = new ArrayList<>();
    for (Node<E> e : graph.values()) {
        if (e.isHead())
            heads.add(e);
    }
    return heads.iterator();
}

Java 8版本:

Iterator<Node> s = graph.values().stream().filter(n -> n.isHead()).iterator();

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