Movatterモバイル変換


[0]ホーム

URL:


Menu
×
See More 
Sign In
+1 Get Certified Upgrade For Teachers Spaces Get Certified Upgrade For Teachers Spaces
   ❮     
     ❯   

Java Tutorial

Java HOMEJava IntroJava Get StartedJava SyntaxJava OutputJava CommentsJava VariablesJava Data TypesJava Type CastingJava OperatorsJava StringsJava MathJava BooleansJava If...ElseJava SwitchJava While LoopJava For LoopJava Break/ContinueJava Arrays

Java Methods

Java MethodsJava Method ParametersJava Method OverloadingJava ScopeJava Recursion

Java Classes

Java OOPJava Classes/ObjectsJava Class AttributesJava Class MethodsJava ConstructorsJava this KeywordJava ModifiersJava EncapsulationJava Packages / APIJava InheritanceJava PolymorphismJava super KeywordJava Inner ClassesJava AbstractionJava InterfaceJava AnonymousJava EnumJava User InputJava Date

Java Errors

Java ErrorsJava DebuggingJava ExceptionsJava Multiple ExceptionsJava try-with-resources

Java File Handling

Java FilesJava Create FilesJava Write FilesJava Read FilesJava Delete Files

Java I/O Streams

Java I/O StreamsJava FileInputStreamJava FileOutputStreamJava BufferedReaderJava BufferedWriter

Java Data Structures

Java Data StructuresJava CollectionsJava ListJava ArrayListJava LinkedListJava List SortingJava SetJava HashSetJava TreeSetJava LinkedHashSetJava MapJava HashMapJava TreeMapJava LinkedHashMapJava IteratorJava Algorithms

Java Advanced

Java Wrapper ClassesJava GenericsJava AnnotationsJava RegExJava ThreadsJava LambdaJava Advanced Sorting

Java Projects

Java Projects

Java How To's

Java How Tos

Java Reference

Java ReferenceJava KeywordsJava String MethodsJava Math MethodsJava Output MethodsJava Arrays MethodsJava ArrayList MethodsJava LinkedList MethodsJava HashMap MethodsJava Scanner MethodsJava File MethodsJava FileInputStreamJava FileOutputStreamJava BufferedReaderJava BufferedWriterJava Iterator MethodsJava Collections MethodsJava System MethodsJava Errors & Exceptions

Java Examples

Java ExamplesJava CompilerJava ExercisesJava QuizJava ServerJava SyllabusJava Study PlanJava Interview Q&AJava Certificate


JavaLinkedHashMap


Java LinkedHashMap

ALinkedHashMap stores keys and values, and keeps them in the same order you put them in.

It is part of thejava.util package and implements theMap interface.

Tip: UseLinkedHashMap when you want predictable iteration order (insertion order).


Create a LinkedHashMap

Create aLinkedHashMap object calledcapitalCities that will storeString keys andString values:

Example

import java.util.LinkedHashMap; // Import the LinkedHashMap classLinkedHashMap<String, String> capitalCities = new LinkedHashMap<>();

Now you can use methods likeput() to add key/value pairs,get() to retrieve a value by key, andremove() to delete an entry - all while maintaining insertion order.


Add Items

Use theput() method to add items to theLinkedHashMap:

Example

// Import the LinkedHashMap classimport java.util.LinkedHashMap;public class Main {  public static void main(String[] args) {    LinkedHashMap<String, String> capitalCities = new LinkedHashMap<>();    capitalCities.put("England", "London");    capitalCities.put("India", "New Dehli");    capitalCities.put("Austria", "Wien");    capitalCities.put("Norway", "Oslo");    capitalCities.put("Norway", "Oslo"); // Duplicate    capitalCities.put("USA", "Washington DC");    System.out.println(capitalCities);  }}

Try it Yourself »

Output: The items will appear in the order they were added (e.g., {England=London, India=New Dehli, Austria=Wien, Norway=Oslo, USA=Washington DC}).

Note: Duplicates like "Norway" are ignored.


Access an Item

Useget() with a key to get its associated value:

Example

capitalCities.get("England");

Try it Yourself »


Remove an Item

Useremove() to remove an item by key:

Example

capitalCities.remove("England");

Try it Yourself »

Useclear() to remove all items:

Example

capitalCities.clear();

Try it Yourself »


LinkedHashMap Size

Usesize() to check how many key/value pairs are in the map:

Example

capitalCities.size();

Try it Yourself »

Note: The size only counts unique keys. If a key is added more than once, only the latest value is kept.


Loop Through a LinkedHashMap

You can loop through aLinkedHashMap using a for-each loop. Use:

  • keySet() to get all keys
  • values() to get all values

Example

// Print keysfor (String key : capitalCities.keySet()) {  System.out.println(key);}

Try it Yourself »

Example

// Print valuesfor (String value : capitalCities.values()) {  System.out.println(value);}

Try it Yourself »

Example

// Print keys and valuesfor (String key : capitalCities.keySet()) {  System.out.println("Key: " + key + ", Value: " + capitalCities.get(key));}

Try it Yourself »


HashMap vs LinkedHashMap

FeatureHashMapLinkedHashMap
OrderNo guaranteed orderInsertion order preserved
PerformanceFaster for random accessSlightly slower due to ordering
DuplicatesKeys must be uniqueKeys must be unique

Tip: UseLinkedHashMap when you want the map to remember the order in which entries were added.


The var Keyword

From Java 10, you can use thevar keyword to declare aLinkedHashMap variable without writing the type twice. The compiler figures out the type from the value you assign.

This makes code shorter,but many developers still use the full type for clarity. Sincevar is valid Java, you may see it in other code, so it's good to know that it exists:

Example

// Without varLinkedHashMap<String, String> capitalCities = new LinkedHashMap<String, String>();// With varvar capitalCities = new LinkedHashMap<String, String>();

Try it Yourself »


The Map Interface

Note: Sometimes you will see bothMap andLinkedHashMap in Java code, like this:

import java.util.Map;import java.util.LinkedHashMap;Map<String, String> capitalCities = new LinkedHashMap<>();

Try it Yourself »

This means the variable (capitalCities) is declared as aMap (the interface), but it stores aLinkedHashMap object (the actual map). SinceLinkedHashMap implements theMap interface, this is possible.

It works the same way, but some developers prefer this style because it gives them more flexibility to change the type later.




×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning.
Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness
of all content. While using W3Schools, you agree to have read and accepted ourterms of use,cookies andprivacy policy.

Copyright 1999-2025 by Refsnes Data. All Rights Reserved.W3Schools is Powered by W3.CSS.


[8]ページ先頭

©2009-2025 Movatter.jp