Keyset and EntrySet

Source: Internet
Author: User

1. Basic overview

Set < Map.entry < K , V >> entryset() returns a set view of the mappings included in this map.

Set < K > keySet() returns a set view of the keys included in this map.

2. Efficiency analysis

For keyset in fact it is traversed 2 times, one is converted to iterator. Remove the value of key from the HashMap one time.

and EntrySet just traversed for the first time, he put the key and value in the entry, so it's fast.

3. Use Example

Map<string, string> maps = new hashmap<string, string> ();
Method one: With EntrySet ()
Iterator<entry<string,string>> it = Maps.entryset (). Iterator ();
while (It.hasnext ()) {
map.entry<string,string> m = It.next ();
String key = M.getkey ();
String value= M.getvalue ();
}
Method Two: jdk1.5 support, with EntrySet () and For-each loops ()
For (map.entry<string, string> m:maps.entryset ()) {
String key = M.getkey ();
String value= M.getvalue ();
}
Method Three: With Keyset ()
Iterator<string> it2 = Maps.keyset (). Iterator ();
while (It2.hasnext ()) {
String key = It2.next ();
String value= Maps.get (key);
}
Method Four: jdk1.5 support. Cycle with keyset () and For-each
For (String M:maps.keyset ()) {
String key = m;
String value= Maps.get (m);
}

The efficiency of the foreach and while is almost identical, and for is relatively slow.

foreach It can replace the for right? Obviously not.
foreach internal in principle or actually Iterator. But it cannot be artificially controlled like iterator, and it cannot be called iterator.remove (), but you cannot use indexes to facilitate access to components.

So this cycle of foreach is generally only suitable for iterations, extracting data display, and not suitable for adding complex operations based on criteria, such as deletion and use.

Keyset and EntrySet

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.