简体   繁体   中英

How to “search” a HashMap then loop the result?

So, Im coding some java. And want to search a HashMap then loop the result, this is my hashmap:

public HashMap<String, String> messages;

BUT! I don't want to loop alle keys, just some. Like searching a MySQL database.

Sorry my english, im Norwegian.

If I understand correctly you want to iterate through the keys of a HashMap. To do this, you need to use Map.keySet() method. This will return a Set which contains all the keys for your map. Alternatively, you can iterate through the entrySet or the values . (Please look at all the links provided for more details.)

Also, I strongly suggest that you check out the Tutorial trail on Collections . You should also familiarize yourself with the Java API docs . In particular, you need to look at the docs for HashMap and Map .

Block类中正确实现equals hashcode并在Hashmap上调用get(Object key)方法,它将进行搜索。

If you want to access all keys and get the values.

public HashMap<String, String> messages;
...
for (final String key : messages.keySet()) {
  final String value = messages.get(key);
  // Use the value and do processing
}

A much better idea is to just use messages.entrySet ...

for (final Map.Entry<String, String> entry : messages.entrySet()) {
  final String key = entry.getKey();
  final String value = entry.getValue();
}

Still very unclear, but you asked how to do both entrySet() and entryKey(). However, entrySet() returns both Key and Value in one data structure:

for( Map.Entry<String,String> entry : messages.entrySet() ) {
    String key = entry.getKey();
    String value = entry.getValue();
    System.out.printf("%s = %s%n", key, value );
}

But typically you don't do this this way, and instead just simply use the Key to get the Value like so yielding a far simpler method for iteration:

for( String key : messages.keySet() ) {
    String value = messages.get(key);

    System.out.printf("%s = %s%n", key, value );
}

There exist no facility to "query" a map like MySQL using only the tools included in default Java. Libraries like apache collections provide Predicates and other filters that can give you query support. Other libraries include guava libraries. For example using apache commons collection:

List<String> keys = new ArrayList<String>(messages.keySet());
CollectionUtils.filter( keys, new Predicate<String>() {
    public boolean evaluate( String key ) {
        if( someQueryLogic ) {
           return true;
        } else {
           return false;
        }
    }
} );

// now iterate over the keys you just filtered

for( String key : keys ) {
    String value = message.get(key);
    System.out.printf("%s = %s%n", key, value );
}

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