Java HashMap – Remove Entries

Learn about removing entries from a HashMap, including removing by key, with an iterator and bulk removal with a filter.

“To live is the rarest thing in the world. Most people exist, that is all.”
― Oscar Wilde

 

1. Introduction

After covering HashMap basics, iteration and searching/sorting, let us look at a few ways of removing entries from a HashMap.

Continue reading “Java HashMap – Remove Entries”

Java HashMap Search and Sort

Search and sort a HashMap by key as well as by value.

“What you stay focused on will grow.”
― Roy T. Bennett

1. Introduction

Having explored HashMap in several previous articles (here and here), let us now learn how to search and sort a HashMap by key as well as value.

Continue reading “Java HashMap Search and Sort”

Java Collections – HashMap

Create a HashMap by parsing CSV. Declare and use a multi-map (a HashMap inside a HashMap).

“Don’t judge each day by the harvest you reap but by the seeds that you plant.”
― Robert Louis Stevenson

Check out the previous parts of this Java Collections Guide: Introduction, Part 1 – Collection, Part 2 – Sets and Part 3 – ArrayList.

1. Introduction

The HashMap implements the Map interface and provides the abstraction of a dictionary mapping of keys to values. It is a part of the Java Collections Framework but does not fall under the Iterable and Collection hierarchy. In this article, we learn how to use HashMaps.

Continue reading “Java Collections – HashMap”

Java Collections – ArrayList

How to properly create and use an ArrayList including adding, retrieving and modifying items.

Check out the previous parts of this Java Collections Guide: Introduction, Part 1 – Collection and Part 2 – Sets.

1. Introduction

The ArrayList is one of the most widely used classes in the Java Collections Framework (if not the entire JDK; that position probably belongs to String). It provides a simple array-like storage of items with dynamically adjusting capacity. In this article, we present some usage patterns of the List and ArrayList.

Continue reading “Java Collections – ArrayList”

How to Convert CSV to JSON in Java

Convert CSV to JSON using Jackson. Use a POJO for conversion or a List & Map for intermediate storage.

“Any fool can know. The point is to understand.”
― Albert Einstein

 

1. Introduction

CSV to JSON conversion is easy. In this article, we present a couple of methods to parse CSV data and convert it to JSON. The first method defines a POJO and uses simple string splitting to convert CSV data to POJO, which in turn is serialized to JSON. The second method uses a more complete CSV parser with support for quoted fields and commas embedded within fields. In this method, we use the Java Collection classes to store the parsed data and convert those to JSON.

Continue reading “How to Convert CSV to JSON in Java”

Java Collections – Set

A Set is a container which does not allow duplicate elements. Common Set implementations include HashSet, LinkedHashSet and TreeSet.

“Quotation, n: The act of repeating erroneously the words of another.”
― Ambrose Bierce, The Unabridged Devil’s Dictionary

Check out the earlier parts of this Java Collections Series: Introduction and Part 1.

1. Introduction

A Set is a container which does not contain duplicate elements. The item method equals() is used to determine whether the object is already present in the Set. At most one null element is allowed in the Set.

Continue reading “Java Collections – Set”

Java Collections – Part 1

Java Collections Framework: learn about adding items, iterating over a collection and removing items.

“Success is not final, failure is not fatal: it is the courage to continue that counts.”
― Winston S. Churchill

Check out the first part of this Java Collections Series: Introduction.

1. Introduction

Let us learn about Java Collections and the various operations applicable to collections in general. Since the Collection interface is implemented by most of the classes in the Collections Framework (except Map and friends), the methods described here apply to all those classes.

Continue reading “Java Collections – Part 1”

Java Collections

Java Collections Framework: An Introduction to the class hierarchy.

“Any fool can know. The point is to understand.”
― Albert Einstein

1. Introduction

Java Collections Framework is an architecture for storing, managing and manipulating collections of objects. It provides many data structures and algorithms commonly used for dealing with collections. For example: searching and sorting. Many details about storing objects are abstracted away (meaning you do not have to deal with it in code). An unified interface is provided to manipulate them e.g for adding and removing entries.

Continue reading “Java Collections”

Java HashMap Examples

1. Introduction

A HashMap is a map of keys to values which uses a hash table for implementation. The HashMap organizes the keys into buckets based on the value of the hashCode() of the key. It provides constant-time performance for get and put operations. What this means is that the time taken by get and put operations does not depend on the size of the map.

Continue reading “Java HashMap Examples”

Java ArrayList Examples

1. Introduction

The ArrayList in Java is one of the most used classes in the JDK. It is an implementation of a resizable array with a range of useful methods for manipulating the array. In this article, we present some of the usage patterns of the ArrayList.

The ArrayList is a concrete implementation of the List interface. As such, it is fine to refer to List instead of ArrayList when the implementation detail does not matter. The examples below use List instead of ArrayList when this difference is not relevant.

2. Array vs ArrayList

A regular array in java is a container which holds a fixed number of elements of a specific type. The following (stringArray) is a declaration of an array of String objects and is initialized to an array enough to store 20 strings.

String[] stringArray = new String[20];

An ArrayList for storing Strings is defined as shown below. The number 20 is an indication to the ArrayList class to reserve enough space for 20 strings.

ArrayList<String> stringList = new ArrayList<String>(20);

Some of the differences between the two:

  • Addition: The stringArray can store upto 20 strings. If you need to store more later on, you will have to re-initialize the array and copy the contents from the old array. With the ArrayList, you can add more than 20 strings without worrying about the capacity.
  • Removal: With the ArrayList it is easy to remove entries, either at a particular index or a range or a particular object. Not so easy with the array. You will need loops and other boiler-plate code to manage the removal in your code.

3. Creating an ArrayList

As already shown above you can create an ArrayList using the constructor. To create an empty ArrayList with a capacity for 10 Objects:

ArrayList<Object> objArray = new ArrayList<>();

To create an ArrayList from another Collection such as a Set or a List, you can use:

Set<String> stringSet = ..;
List<String> list = new ArrayList<String>(stringSet);

What if you need to create a List from a bunch of objects already lying around in your code? You can use Arrays.asList() as follows:

List<String> list = Arrays.asList("Apple", "Banana", "Orange");

The following selects lines from a text file using Java 8 streams.

List<String> lines = Files
    .lines(Paths.get(textFile))
    .filter(x -> x.length() > 50)
    .collect(Collectors.toList());

4. Convert Array to ArrayList

As presented above, it is simple to convert to a List if you have a plain array of objects.

List<String> a = Arrays.asList(args);

The above is suitable if you have an array of objects. What if you have an array of a primitive type, say an int? Here is how you can handle that case.

int[] array = { 2, 4, 5 };
List<Integer> list = Arrays
    .stream(array)
    .boxed()
    .collect(Collectors.toList());

5. Convert ArrayList to Array

The List interface provides a method toArray() which creates and returns a new array containing all the elements in the ArrayList.

List<String> strList = ...;
String[] strArray = strList.toArray();

6. Add to ArrayList

Use the method add() to add items to a List. This invocation adds elements at the end of the list.

List<String> strList = new ArrayList<>();
strList.add("Apple");
strList.add("Banana");
strList.add("Orange");
strList.stream().forEach(System.out::println);

// prints
Apple
Banana
Orange

To add all elements of a collection, use addAll().

List<String> modList = new ArrayList<>();
modList.addAll(strList);
modList.add("Melon");

7. UnsupportedOperationException

The following code results in an UnsupportedOperationException. The reason is than Arrays.asList() returns a fixed sized list backed by the input array. So you cannot add elements to the List returned by Arrays.asList().

A simple solution is to create a new ArrayList from the original list as follows:

List<String> strList = Arrays.asList("Apple", "Banana", "Orange");
List<String> modList = new ArrayList<>(strList);
modList.add("Melon");

Or you could use Java 8 streams:

List<String> modList = strList
	.stream()
	.collect(Collectors.toList());
modList.add("Melon");
modList.stream().forEach(System.out::println);

// prints:
Apple
Banana
Orange
Melon

8. Remove from ArrayList

Removal of items from a List is also easy. Remove an element at a particular index.

List<String> modList = new ArrayList<>();
modList.addAll(strList);
modList.add("Melon");
modList.remove(2);

// contains:
Apple
Banana
Melon

Remove a particular object as shown below. Note: The equals() method is used for checking whether to remove the object. It works as shown for String. For another class, equals() might be defined in terms of memory addresses, in which case the same object instance must be passed in to remove it.

List<String> modList = new ArrayList<>();
modList.addAll(strList);
modList.add("Melon");
modList.remove("Orange");

// contains
Apple
Banana
Melon

What if you want to remove an object with some specific characteristic. Use the removeIf() method with the predicate. The methods removes all elements that match the predicate.

List<String> modList = new ArrayList<>();
modList.addAll(strList);
modList.add("Melon");
modList.removeIf(x -> x.endsWith("e"));

// contains
Banana
Melon

Remove all objects from one List that are found in another List using removeAll().

List<String> modList = new ArrayList<>();
modList.addAll(strList);
modList.add("Melon");
modList.removeAll(Arrays.asList("Banana", "Kiwi"));

// contains
Apple
Orange
Melon

Summary

This article explained Java arrays and ArrayList from the perspective of a beginner. We showed creation and initialization of ArrayList. The ArrayList provides a bunch of methods to add and remove elements from the list. In some cases, the List created may not be modifiable in which case an exception is thrown when you try to modify it.