How-to articles, tricks, and solutions about COLLECTIONS

How to sort a Map<Key, Value> by values in Java

To sort a Map&lt;Key, Value&gt; by values in Java, you can create a custom comparator that compares the values and pass it to the sort() method of the Map.Entry class.

How to sort an ArrayList in Java

To sort an ArrayList in Java, you can use the Collections.sort method.

Java - How to create new Entry (key, value)

To create a new key-value pair in a Map in Java, you can use the put method.

Java 8 Distinct by property

To get a list of distinct elements by a property in Java 8, you can use the distinct() method of the Stream interface and the map() method to extract the property from each element.

Java: Get first item from a collection

To get the first item from a collection in Java, you can use the iterator() method to get an iterator for the collection, and then call the next() method on the iterator to get the first element.

Printing HashMap In Java

To print the contents of a HashMap in Java, you can use the entrySet() method to get a set of key-value pairs and then iterate over the set to print the keys and values.

Ways to iterate over a list in Java

There are several ways to iterate over a List in Java. Here are some of the most common approaches:

What are the differences between a HashMap and a Hashtable in Java?

There are several differences between a HashMap and a Hashtable in Java:Synchronization: Hashtable is synchronized, while HashMap is not.

When to use LinkedList over ArrayList in Java?

In Java, both ArrayList and LinkedList are implementations of the List interface that allow you to store a collection of objects in a specific order. However, they are implemented differently and have different performance characteristics.

Why is there no SortedList in Java?

There is no SortedList class in the Java standard library because the List interface already provides a way to store elements in a specific order.

1 2