Skip to content

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

Leave a Reply

Your email address will not be published.