- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to keep the insertion order with Java LinkedHashMap?
To keep the insertion order with LinkedHashMap, use Iterator. Let us first create a HashMap and add elements to it −
LinkedHashMap<String, String>lHashMap = new LinkedHashMap<String, String>(); lHashMap.put("1", "A"); lHashMap.put("2", "B"); lHashMap.put("3", "C"); lHashMap.put("4", "D"); lHashMap.put("5", "E"); lHashMap.put("6", "F"); lHashMap.put("7", "G"); lHashMap.put("8", "H"); lHashMap.put("9", "I");
Now, get the values with the values() method. Iterate through the elements and display them −
Collection collection = lHashMap.values(); Iterator i = collection.iterator(); while (i.hasNext()) { System.out.println(i.next()); }
Example
import java.util.Collection; import java.util.Iterator; import java.util.LinkedHashMap; public class Demo { public static void main(String[] args) { LinkedHashMap<String, String>lHashMap = new LinkedHashMap<String, String>(); lHashMap.put("1", "A"); lHashMap.put("2", "B"); lHashMap.put("3", "C"); lHashMap.put("4", "D"); lHashMap.put("5", "E"); lHashMap.put("6", "F"); lHashMap.put("7", "G"); lHashMap.put("8", "H"); lHashMap.put("9", "I"); Collection collection = lHashMap.values(); Iterator i = collection.iterator(); while (i.hasNext()) { System.out.println(i.next()); } } }
Output
A B C D E F G H I
Advertisements