[Java] [Java] Get List / Map elements with Iterator

3 minute read

table of contents

  • at first
    –What is Iterator?
    –List Iterator
    –Map Iterator
    –From generic expression to extended for statement
    –Summary
  • in conclusion

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.

  • Please read the class name / variable name etc. in the code in the text as appropriate.
  • Some parts omit the main method notation.
  • Please let us know if there are any corrections / improvements.

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.

  • next()
    –Returns the next element in iterative processing.
  • hasNext()
    –Returns true if there are more elements in the iteration.
  • remove()
    –Remove the last element returned by the iterator from the underlying collection. (Arbitrary operation)
    ―― ~~ You don’t have to remember ~~ You can remember

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 <reference object type> 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
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`**
```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.