Movatterモバイル変換


[0]ホーム

URL:


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

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 ChallengeJava Method ParametersJava Method OverloadingJava ScopeJava Recursion

Java Classes

Java OOPJava Classes/ObjectsJava Class AttributesJava Class MethodsJava Class ChallengeJava 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 VideosJava CompilerJava ExercisesJava QuizJava Code ChallengesJava ServerJava SyllabusJava Study PlanJava Interview Q&AJava Certificate


JavaTreeMap


Java TreeMap

ATreeMap is a collection that stores key/value pairsin sorted order by key.

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

Tip: UnlikeHashMap, which does not maintain order,TreeMap keeps its keys sorted.


Create a TreeMap

Create aTreeMap that storesString keys andString values:

Example

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

Now you can use methods likeput(),get(), andremove() to manage sorted key/value pairs.


Add Items

Use theput() method to add key/value pairs:

Example

import java.util.TreeMap;public class Main {  public static void main(String[] args) {    TreeMap<String, String> capitalCities = new TreeMap<>();    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 keys are sorted alphabetically (e.g., {Austria=Wien, England=London, India=New Dehli, Norway=Oslo, USA=Washington DC}).

Note: Duplicates like "Norway" will only appear once.



Access an Item

Useget() with the key to access its value:

Example

capitalCities.get("England");

Try it Yourself »


Remove Items

Useremove() to delete a key/value pair by key:

Example

capitalCities.remove("England");

Try it Yourself »

Useclear() to remove all items:

Example

capitalCities.clear();

Try it Yourself »


TreeMap Size

Usesize() to count the number of key/value pairs:

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 TreeMap

Loop through the items of aTreeMap with a for-each loop.

Note: Use thekeySet() method if you only want the keys, and use thevalues() method if you only want the values:

Example

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

Try it Yourself »

Example

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

Try it Yourself »

Example

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

Try it Yourself »


TreeMap vs HashMap

FeatureHashMapTreeMap
OrderNo guaranteed orderSorted by keys
Null KeysAllows one null keyDoes not allow null keys
PerformanceFaster (no sorting)Slower (maintains sorted order)

Tip: UseHashMap for performance, andTreeMap when you need sorted keys.


The var Keyword

From Java 10, you can use thevar keyword to declare aTreeMap 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 varTreeMap<String, String> capitalCities = new TreeMap<String, String>();// With varvar capitalCities = new TreeMap<String, String>();

Try it Yourself »


The Map Interface

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

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

Try it Yourself »

This means the variable (capitalCities) is declared as aMap (the interface), but it stores aTreeMap object (the actual map). SinceTreeMap 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-2026 by Refsnes Data. All Rights Reserved.W3Schools is Powered by W3.CSS.

-->
[8]ページ先頭

©2009-2026 Movatter.jp