List Set Map in Java Example

Become familiar with the most used collection interfaces

We can start defining a collection itself: A group of elements contained into a single one, for example:

Element: Yu-Gi-Oh card
Collection: Yugi's deck (set of cards belonging to Yugi)

In programming, the idea is the same. You could have a single object or a group of the same object inside a collection. Specifically in Java, a collection refers to any group of objects stored in a single structure belonging to some class stored in java.util. There is 4 main collection interfaces you should be familiar with:

  • List
  • Set
  • Map
  • Queue

All of those interfaces extend from the main interface Collection, except the Map interface. Map is a different type, with its own purpose. Let's start exploring the Collection interface's methods:

  • add(E Element) : Boolean, inserts a new element.
  • remove(E Element) : Boolean, removes an element from the collection.
  • isEmpty() : Boolean, returns true if the collection has no elements.
  • size() : Returns how many elements we have stored in the collection.
  • clear(): void, removes all elements from the collection.
  • contains(E Element): Boolean, verifies if some element is stored in the collection.

Let's see how those methods work using the List interface:

Using List

Use List if you need an ordered collection allowing duplicate elements. You have 2 different implementations of this interface:

  • ArrayList: A resizable array, every time it reaches the limit, automatically doubles its size. Good performance when looking over the elements (even faster than adding or removing).
  • LinkedList: Implements List and Queue. A good option when you need add or remove elements constantly, slower when you need to lookup over all the elements. LinkedList is often used as a Queue instead of a common List.

There are 2 more "old" classes: Vector and Stack. Vector does the same as ArrayList but slowly, Stack is unused and commonly replaced by ArrayDeque.

List has the same methods from the Collection interface, but also overloads some of them for working with indexes and implements a few ones. The entire detail is in the official docs:

Using Set

Similar to List, but it does not accept duplicated elements and does not keep a defined order. We can find the following implementations:

  • HashSet: Uses a HashTable for storing objects. It means, it uses the hashCode() method from the stored objects to retrieve them more efficiently. Use this implementation if you don't mind the order of stored elements.
  • TreeSet: Store objects ordered in a tree structure. The main benefit is all elements are always ordered, but it has a performance cost when you need to add more elements because it needs first to find the right position (keeping the order).

The Set interface does not add any "extra" methods.

Using Queue

Let's define Queue before Map just to finish with the Collection interface. Use Queue when you need your elements are added/removed in a specific order. Similar to the real world, a Queue is the structure you use when you want to process elements in some order, for example, when you buy tickets for the cinema, the first one in the queue will be the first one to buy the tickets, then this person will disappear from the queue.

The two Queue implementations are LinkedList, seen before and ArrayDeque, used to store elements in a resizable array (More efficient than LinkedList). Also, Queue adds more methods to the already inherited from the Collection interface:

  • add(E Element): Add a new element at the end or throws an exception.
  • E element(): Returns the next element or throw an exception if the queue is empty.
  • offer(E Element): Add a new element and returns if the operation was successful.
  • E remove(): Remove the element and returns the next one.
  • push(E Element): Add a new element in the front of the queue.
  • E poll(): Return and remove the next element or null if empty.
  • E peek(): Return next element or null if empty.
  • E pop(): Return and remove the next element or throw an exception if empty.

Using Map

Map is outside the Collection interface, so you won't see the same methods as the previous interfaces. Map is a special collection, used when you need to store elements in a key: value format, for example, you need to save your contact numbers. You will identify each number by the name it has:

  • name -> key
  • number -> value

Like the other interfaces, Map has its own implementations:

  • HashMap: Store the keys in a HashTable, do not order the elements. If you need the elements ordered, you can use a LinkedHashMap instead.
  • TreeMap: Maintains all elements sorted by key.

The Map interface define the following methods:

  • clear(): Removes all keys and values from the map.
  • isEmpty(): Returns if the map is empty.
  • int size(): Returns the number of entries (key/value pairs) in the map.
  • V get(Object key): Returns the value mapped by key or null if none is mapped.
  • V put(K key, V value): Adds or replaces key/value pair. Returns previous value or null.
  • V remove(Object key): Removes and returns value mapped to a key. Returns null if none.
  • containsKey(Object key): Returns whether the key is on map.
  • containsValue(Object): Returns the value in the map.
  • Set<K> keySet() : Returns set of all keys.
  • Collection<V> values(): Returns Collection of all values.

Collections in practice

As you may see, each interface has its own purpose to manage collections. The secret is to understand your use case and create the relationship with the proper implementation, for example:

"You have a book's collection. The collection is accessed constantly and people search the book by author name. Which is the most suitable implementation?"

The first thing to identify: Each book has an author and a book name. It means {author: bookName} , being author the key. Therefore, we need a Map. Second, is accessed in real time, so we need to be able to return the right element faster. The best option would be a TreeMap, because it maintains all elements sorted and we don't need to iterate over the entire collection.

In case you want to go deeper, I strongly recommend you to read about the code implementations for each collection type and the data structure used, it will give you a good understanding of what's happening inside:

See you in the next article ;)

mcguirearniagaten.blogspot.com

Source: https://medium.com/javarevisited/java-understanding-list-set-map-and-queue-4330cf54596d

0 Response to "List Set Map in Java Example"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel