[Java] Get List / Map elements with Iterator

table of contents

at first

When you touch Map / List in Java,

-** I want to do something for all the elements of List! ** ** -** I want to iterate over all Map elements! ** **

I think there are quite a few moments like that. This ** Iterator ** is convenient in such a case.

Please refer to it as it is summarized with the actual code.

What is Iterator

Definition

An iterator (English: iterator) is an abstraction of iterative processing for each element of an array or similar collective data structure (collection or container) in a programming language. In a real programming language, it appears as an object or grammar. In JIS, it is translated as iterator (hanpukushi). wikipedia

As mentioned above, the ** interface ** for performing ** iterative processing ** on ** arrays and similar data ** is called Iterator.

Iterator method

The following two methods are declared in the Iterator class.

The above two are important, and iterative processing mainly uses next () and hasNext (). When using Iterator in another class, ** override ** the method. "Arbitrary operation" of remove () means "some objects called Iterator do not support".

notation

When used, instantiate with ```Iterator object name `` `

Below, we will actually check how to use it in each class.

List-based Iterator

Since the List class implements ** Iteratable interface **, you can get an Iterator type object just by calling a method. List class details (Oracle HP)

IteratorDemo.java


public void IteratorDemo(){
//List creation
	List<String> list = new ArrayList<String>(); 
	list.add("Dog");                           
	list.add("monkey");                           
	list.add("pheasant");                                                
//Get iterator, call method
	Iterator<String> itList = list.iterator();
//display
	while (itList.hasNext()){                    
		String s = itList.next();
		System.out.println(s);
	}
}
Execution result:
Dog
monkey
pheasant

Map-based Iterator

Since ** Iterator interface is not implemented in Map class **, iterator is acquired after making it a class type object that implements Iterator interface once.

IteratorDemo.java


//Map creation//                                                                             
	Map<Character, String> map = new HashMap<Character, String>();                      
	map.put('A', "Arufa");                                                               
	map.put('B', "Bravo");                                                               
	map.put('C', "Charlie");                                                              
                                                                                        
//Get iterator, call method//                                                                                        
	// keySet()Get the key list as a Set type object with
	Iterator<Character> itMapKey = map.keySet().iterator();                             
                                                                                        
	// values()Get a list of values as a Collection type object with
	Iterator<String> itMapValue = map.values().iterator();                              
                                                                                        
	// entrySet()With Set<Map.Entry<K, V>Get a key / value combination as a type object
	Iterator<Map.Entry<Character, String>> itEntry = map.entrySet().iterator();         
                                                                                        
                                                                                        
//display//                                                                                
	while (itMapKey.hasNext()){                                                         
		char key = itMapKey.next();                                                     
		System.out.println(key);                                                        
	}                                                                                   
                                                                                
	while (itMapValue.hasNext()){                                                       
		String value = itMapValue.next();                                               
		System.out.println(value);                                                      
	}                                                                                   
                                                                               
	while(itEntry.hasNext()){                                                           
		Map.Entry<Character, String> entry = itEntry.next();                            
		System.out.println(entry);                                                      
	}                                                                                                                                    
Execution result:
A
B
C
Arufa
Bravo
Charlie
A=Arufa
B=Bravo
C=Charlie

From generic expression to extended for statement

In the above code example, the output was performed using the generics ** "<>" **, but the extended for statement can also be used. The output method for each List / Map for statement is as follows.

//The display result is the same as the code in the "Map iterator" section.

//Show all the contents of the List
for (String value : list){    
	System.out.println(value);
}                             
//Show all Map keys
for (char key : map.keySet()){ 
	System.out.println(key);   
}
//Show all map values
for (String value : map.values()){ 
	System.out.println(value);     
}
//Map key / value combinations(entry)Show all
for (Map.Entry<Character, String> entry : map.entrySet()){
	System.out.println(entry);                            
}                                                                                                                   

Summary

--List class can use Iterator as it is --Map class is used after converting the value to an object of the type that Iterator is implemented. --The methods used when fetching each value of Map system are as follows.

Elements you want Method name Return value
List of keys map.keySet() Set type
List of values map.values() Collection type
List of key / value combinations map.entrySet() Collection<Entry<K, V>>Mold

At the end

Thank you for reading this far.

There are some parts that haven't been touched on yet, so I'd like to summarize them someday.

I saw some articles like "Implement Iterator in my own class", so I'd like to summarize them someday.

Then.

Recommended Posts

[Java] Get List / Map elements with Iterator
Java8 list conversion with Stream map
[Java] [ibatis] How to get records of 1-to-N relationship with List <Map <>>
[Java] Get the file path in the folder with List
I want to get along with Map [Java beginner]
For Java beginners: List, Map, Iterator / Array ... How to convert?
[Java] Delete the elements of List
Get Null-safe Map values in Java
Make a list map with LazyMap
[Java] Convert 1-to-N List to Map
JAVA (Map)
Get Timestamp with Azure BlobStorage Java SDK
[Java] Get the date with the LocalDateTime class
Get a list of S3 files with ListObjectsV2Request (AWS SDK for Java)
List, Set, Map
Java memorandum (list)
Clone Java List.
Get block information with Hyperledger Iroha's Java SDK
Array / list / map
[Java] Get images with Google Custom Search API
[Java] Map comparison
[LeJOS] Get EV3 sensor value remotely with Java
About List [Java]
Get along with Java containers in Cloud Run
[Java] Sort ArrayList with elements of your own class
List processing to understand with pictures --java8 stream / javaslang-
Get a list of MBean information for Java applications
Experienced Java users get started with Android application development
Get Azure App Service for Java Configuration with System.getEnv ()
[Java] Get the date 10 days later with the Calendar class
Get started with serverless Java with the lightweight framework Micronaut!
[java] sort in list
Install java with Homebrew
[Java] Get miscellaneous dates
Change seats with java
Install Java with Ansible
[Java] Stream API / map
Comfortable download with JAVA
Switch java with direnv
About Java Array List
Enum reverse map Java
[Java] Initialize, add, get
Java bidirectional map library
Download Java with Ansible
Let's scrape with Java! !!
Build Java with Wercker
Get started with Gradle
[Memo] Java Linked List
Endian conversion with JAVA
[Java] Get Map key / value pairs using extended for statement
[Java] Get Charset with Apathce Tika / Initialize String from Charset [Kotlin]
First year Java developers on udemy get started with PHP
I want to make a list with kotlin and java!
Problems with Dijkstra's algorithm using PriorityQueue and adjacency list (java)
List processing to understand with pictures --java8 stream / javaslang --bonus
About the behavior when doing a file map with java