Convert TreeMap to ArrayList in Java Example

This example shows how to convert TreeMap to ArrayList in Java. The example also shows how to convert TreeMap keys, values, or entries to an ArrayList.

How to convert TreeMap to ArrayList in Java?

There are several ways using which we can convert TreeMap keys, values or entries to ArrayList as given below.

1. Convert TreeMap keys to ArrayList

Get all the keys of the TreeMap object using the keySet method. The keySet method returns a Set view of all the keys. Once we have the key set, we can convert it to an ArrayList using the constructor as given below.

Output

2. TreeMap values to ArrayList

Get all the values of the TreeMap object using the values method. The values method returns a Collection view of all the values. Once we have the values collection, we can convert it to an ArrayList using the constructor as given below.

Output

3. TreeMap entries to ArrayList

Get all the entries stored in the TreeMap using the entrySet method. The entrySet method returns a Set view of all the entries. Once we have the entry set, we can convert it to an ArrayList using the constructor as given below.

Output

As you can see from the output, the entries are sorted automatically by the TreeSet class in the key’s natural order (that is ascending for the type Integer).

You can also convert keys, values, and entries to the LinkedList instead of an ArrayList using the same process.

This example is a part of the TreeMap in Java Tutorial.

Please let me know your views in the comments section below.

References:
Java 8 TreeMap

About the author

RahimV

RahimV

My name is RahimV and I have over 16 years of experience in designing and developing Java applications. Over the years I have worked with many fortune 500 companies as an eCommerce Architect. My goal is to provide high quality but simple to understand Java tutorials and examples for free. If you like my website, follow me on Facebook and Twitter.

Add Comment

Your email address will not be published. Required fields are marked *