Pages

Showing posts with label Collections. Show all posts
Showing posts with label Collections. Show all posts

Thursday, September 5, 2024

Anonymous Comparator In Java For Sorting

1. Overview

In this tutorial, We'll learn how to sort arrays or lists using an anonymous comparator in java.

A complete guide on how to use comparator in java?

Anonymous class means creating the class and providing the implementation at the same without a class name.

For example, we have an interface Job and it has the method post() to post the new job. here, a new job1 instance is created for the implementation class of Job interface without a class name.

Example 1

interface Job {
	void post();
}

Job job1 = new Job() {

	@Override
	public void post() {
		System.out.println("Posting job 1 now");

}


This is similar to the anonymous implementation of the abstract class or interface. This is the actual implementation of the Comparator without creating a class and implementing the Comparator interface.

Wednesday, December 22, 2021

Java List or ArrayList Max Size (With Examples)

1. Overview

In this tutorial, We'll understand what is the limit of ArrayList or List implementations that can hold the maximum size.

But this is completely different from finding maximum value from ArrayList.

Before finding the max size of ArrayList, we need to understand that ArrayList collection API is implemented based on the ordinary arrays of java.

If the new ArrayList<Integer>(5) then a new ArrayList with the size of 5 is created and it can store 5 integer values.

Java List or ArrayList Max Size

Friday, December 17, 2021

Java ArrayList Insert/Replace At Index

1. Overview

In this tutorial, We'll learn how to insert or replace an element at a specified index into ArrayList java.

Use the ArrayList.add(int index, Object value) method to add any object or element at the specific index of ArrayList and use ArrayList.set(int index, E  value) to replace the value at the specific index of ArrayList in java.

Let us explore the examples

All examples shown in this article are on GitHub and a link is given at the end of the post.

Java ArrayList Insert/Replace At Index

Saturday, December 11, 2021

Java TreeMap Comparator

1. Overview

In this tutorial, We'll learn how to add a custom comparator to the TreeMap in java to sort by key and also sort by values.

If you are new to java comparators, please read an in-depth article on Java comparators with java 8 stream api. 

Java TreeMap Comparator

Tuesday, December 7, 2021

Java 8 Comparator Comparing Reverse Order

 

1. Overview

In this tutorial, We'll learn how to use a comparator to sort the collection in reverse order.

In Java 8, Comparator interface is added with the reverse() method to reverse the collection using the existing comparator instead of creating another custom comparator.

First, let us learn how to reverse the comparator for comparing the objects from the collection before java 8 and next using Java 8 Comparator new methods.


Java 8 Comparator Comparing Reverse Order

Monday, December 6, 2021

Java 8 Comparator Lambda Examples

1. Overview


In this tutorial, We'll learn how to use the Comparator interface with lambda expression in Java 8 onwards.

Lambda expression is to replace the anonymous implementations and to reduce the boilerplate code.

This makes the code cleaner and focus more on the business logic rather than semantics.


Java community provided a few sets of rules and guidelines in creating the lambda statements.

Lambda syntax and invalid one are discussed in detail in the previous discussions "java 8 lambda expressions".

First, we will see the examples without lambda and then the next section will see the equivalent lambdas.

For sorting to work with lambda comparator, we have to use the Collections.sort() method.

Java Comparator Lambda Examples

Saturday, December 4, 2021

Java Comparator

1. Overview

In this tutorial, We'll learn how to use the Comparator interface in java.

A comparator interface is used to order the user-defined object in sorted order. This comparator interface has the capability to compare the same type of objects.

Comparator is used to sort the object in ascending or descending order.

We will write the example programs on custom objects with a single field or property.
And also how to sort the collection such as a list or set by multiple properties.

Java Comparator


Friday, December 3, 2021

Java PriorityQueue With Comparator

1. Overview

In this tutorial, We'll learn how to use the comparator with the PriorityQueue class in java to implement our own custom priority field.

This post covers in older java version and with java 8 later also.

PriorityQueue is a normal queue but it has the special ability to process them based on its priority field. That means each object inside the PriorityQueue is associated with the "priority" field.

This field decides which object should be popped out from the queue. Whichever is having the highest priority will be coming out first and the lowest priority one comes last from the PriorityQueue.

Let us write simple examples to understand PriorityQueue with a custom comparator.


Java PriorityQueue With Comparator

Saturday, November 27, 2021

Java HashSet class with Examples, Usage

Java Collection API HashSet Class


In Java, HashSet is defined as class and introduced in version 1.2 as part of Collection api. It is available in package java.util.HashSet.

HashSet is implemented based on Set interface to not allow duplicate values.

Java-Hashset


Monday, November 22, 2021

Java HashMap with Example Programs + Java 8 Methods

1. Introduction


In this tutorial, We'll be learning HashMap API and its usage. HashMap is one of the implementations of the Map interface. HashMap is widely used in the realtime applications to store the key-value pair. This supports all kinds of operations needed on a daily basis to work on the dataset. This comes with most used built-in utility methods to add the values into map(), replace(), remove(), get() methods. We'll be showing java 8 new API changes to the HashMap such as compute(), replaceAll(), computeIfAbsent(), computeIfPresent(), merge() methods.

public class HashMap<K,V> extends AbstractMap<K,V>
    implements Map<K,V>, Cloneable, Serializable



Examples of HashMap In Java and Understand HashMap Real-Time usage



HashMap helps one object as an index to another object as the value. List index will be always a number whereas in Map it can be String, Integer, Float or Student or Trade objects.

Let us explore the most useful methods step by step.

Wednesday, November 17, 2021

Java ArrayList Add() - How to add values to ArrayList?

How to add values to ArrayList?

In this post, we will learn how to add elements to ArrayList using java inbuilt methods. ArrayList class in java has been implemented based on the growable array which will be resized size automatically. Maintains the order of insertion of values added to it and permits adding all kinds of values including primitives, user-defined classes, wrapper classes and null values.

java arraylist add


Java ArrayList add methods:

Java ArrayList add method is overloaded and the following are the methods defined in it.

1) public boolean add(E e)
2) public void add(int index, E element)

Sunday, June 13, 2021

Java - How to Convert Java Array to Iterable?

1. Overview

In this tutorial, We will learn how to convert java array to iterable in different ways with example programs.

First we will go thorough the basic one how to iterate over the array values. Next, how to convert the array to Iterable using legacy java api and finally using java 8 api for java array iterator.

Bonus section on how to convert string to iterable with a delimiter.

Java - How to Convert Array to Iterable?



2. Create a iterator over the array using loops


Running a for loop over a array to create iterable logic to get the each value from array based on the index.
package com.javaprogramto.arrays.toiterabale;

/**
 * 
 * Array Iterate example using loops
 * 
 * @author javaprogramto.com
 *
 */
public class ArrayIterate {

	public static void main(String[] args) {

		// string array
		String[] names = new String[] {"john", "Amal", "Paul"};
		
		// iterating array over its values.
		for(int index=0; index< names.length ; index++) {
			System.out.println(names[index]);
		}
	}
}

 
Output:
john
Amal
Paul
 

3. Convert Java Array to Iterable using legacy java before JDK 8


First we will convert the array to list using Arrays.asList() method. Next, convert list to Iterable in java using list.iterator() method.

Finally, iterate the iterator over the while loop to get the all the values.

Array to Iterable Example:
package com.javaprogramto.arrays.toiterabale;

import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

/**
 * 
 * Example to convert Java Array to Iterable before Java 8
 * 
 * @author javaprogramto.com
 *
 */
public class JavaArrayToIterableExample {

	public static void main(String[] args) {

		// string array
		String[] names = new String[] {"john", "Amal", "Paul"};
		
		// string array to list conversion
		List<String> namesList = Arrays.asList(names);
		
		// List to iterable
		Iterator<String> it = namesList.iterator();
		
		// printing each value from iterator.
		while(it.hasNext()) {
			System.out.println(it.next());
		}
	}
}
 
Output:
john
Amal
Paul
 

4. Convert Java Array to Iterable Using Java 8 Stream


In the above section, we called Arrays.asList() method to convert the array to List. But, now will use another method from java 8 stream api Arrays.stream(array) method which takes input array and returns a Stream of array type.

Arrays.stream() method provides the arrays to access the stream api and use the power of parallel execution on larger arrays.

But for now, after getting the Stream<String> object then you need to call the iterator() method on stream to convert Stream to iterable.

Do not worry, if you are new to the java 8, the below program is break down into multiple steps. And also provided a single line solution.
import java.util.Arrays;
import java.util.Iterator;
import java.util.stream.Stream;

/**
 * 
 * Example to convert Java Array to Iterable using Java 8 Arrays.stream()
 * 
 * @author javaprogramto.com
 *
 */
public class JavaArrayToIterableExampleJava8 {

	public static void main(String[] args) {

		// string array
		String[] names = new String[] {"john", "Amal", "Paul"};

		System.out.println("Multi line solution");
		// Convert string array to Stream<String>
		Stream<String> namesList = Arrays.stream(names);
		
		// Stream to iterable
		Iterator<String> it = namesList.iterator();
		
		// printing each value from iterator.
		while(it.hasNext()) {
			System.out.println(it.next());
		}
		
		// singel line
		System.out.println("\nIn single line");
		Arrays.stream(names).iterator().forEachRemaining(name -> System.out.println(name));
	}
}
 

Multiline and single line solutions provide the same output. If you are going to use in the realtime project then use it as single line statement as you want to fell like expert and take the advantage of stream power.
Multi line solution
john
Amal
Paul

In single line
john
Amal
Paul

 

5. Bonus - Convert String to Iterable


Applying iterable on string is quite simple if you have understood the above code correctly. What we need is now to convert the String to String array with space or if the string has any delimiter.

After getting the string array then apply the same logic as java 8 streams as below.
public class JavaStringToIterableExampleJava9 {

	public static void main(String[] args) {

		// string 
		String numbers = "1 2 3 4 5 6";

		// string to string array
		String[] numbersArray = numbers.split(" ");

		System.out.println("Multi line solution");
		// Convert string array to Stream<String>
		Stream<String> numbersList = Arrays.stream(numbersArray);
		
		// Stream to iterable
		Iterator<String> it = numbersList.iterator();
		
		// printing each value from iterator.
		while(it.hasNext()) {
			System.out.println(it.next());
		}
		
		// singel line
		System.out.println("\nIn single line");
		Arrays.stream(numbersArray).iterator().forEachRemaining(name -> System.out.println(name));
	}
}
 
Output:
Multi line solution
1
2
3
4
5
6

In single line
1
2
3
4
5
6

 

6. Conclusion


In this article, you've seen how to convert the Array to iterable and get the each value from iterator using legacy and new java 8 api.

And also how to convert String to Iterable in java?



Wednesday, February 3, 2021

Sorting ArrayList in Reverse or Descending Order in Java 8

1. Overview

In this article, We will learn how to sort ArrayList in descending order in java. Sometimes this is referred as collections reverse or decreasing order.

To get the list in the reverse order, we need to use Collections.reverseOrder() and Collections.sort() methods together.

Sorting ArrayList in Reverse or Descending Order in Java 8


2.  Sort ArrayList In Descending order using Collections.reverseOrder()

We have already shown how to sort list in ascending order using Collections.sort() method.

In the below examples, we are using the built-in comparator from the reverseOrder() method and passing it to the Collections.sort() method.


package com.javaprogramto.java8.arraylist;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class ArrayListReverseOrder1 {

	public static void main(String[] args) {

		// Creating ArrayList
		List<Integer> numbersList = new ArrayList<>();

		// Adding values to List
		numbersList.add(150);
		numbersList.add(50);
		numbersList.add(250);
		numbersList.add(500);
		numbersList.add(350);

		// printing before sorting
		System.out.println("Before sorting : " + numbersList);

		// Getting the descending order comparator
		Comparator<Integer> reverseComparator = Collections.reverseOrder();

		// Sorting with the reverse comparator with sort() method.
		// sort() method internally uses this comparator to sort in the descending order
		Collections.sort(numbersList, reverseComparator);

		// printing the final list after reverse order sorting. Original list only
		// sorted.
		System.out.println("After sorting : " + numbersList);
	}
}

 

Output:

Before sorting : [150, 50, 250, 500, 350]
After sorting : [500, 350, 250, 150, 50]
 

3.  Sort ArrayList In Descending order using Collections.reverse()

Next, look at the another way to sort the arraylist in descending order using two methods as below.

Collections.sort(arraylist); --> first sorts the list in the ascending order

Collections.reverse(arraylist); --> Next, reverse the sorted list.

Example:


import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class ArrayListReverseOrder2 {

	public static void main(String[] args) {

		// Creating ArrayList
		List<Integer> numbersList = new ArrayList<>();

		// Adding values to List
		numbersList.add(150);
		numbersList.add(50);
		numbersList.add(250);
		numbersList.add(500);
		numbersList.add(350);

		// printing before sorting
		System.out.println("Before sorting : " + numbersList);

		// sorting the list in the ascending order
		Collections.sort(numbersList);

		// reversing the sorted list into descending order
		Collections.reverse(numbersList);

		// printing the final list after reverse order sorting. Original list only
		// sorted.
		System.out.println("After sorting : " + numbersList);

	}

}
 

This program also produces the same output as in the section 2.

4. Java 8 Sort ArrayList Descending Order

Sorting list in reverse order is pretty easy from stream.sorted(Collections.reverseOrder()) in java 8 api.

We can use parallelStream() method to work efficiently with larger data volumes.

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

public class ArrayListReverseOrder2 {

	public static void main(String[] args) {

		// Creating ArrayList
		List<Integer> numbersList = new ArrayList<>();

		// Adding values to List
		numbersList.add(150);
		numbersList.add(50);
		numbersList.add(250);
		numbersList.add(500);
		numbersList.add(350);

		// printing before sorting
		System.out.println("Before sorting : " + numbersList);

		List<Integer> descendingList = numbersList.stream()
				.sorted(Collections.reverseOrder())
				.collect(Collectors.toList());

		// printing the final list after reverse order sorting. Original list only
		// sorted.
		System.out.println("After sorting : " + descendingList);
	}
}
 


5. Conclusion

In this article, We have seen how to sort the ArrayList in descending order in older and new java 8 streams.

GitHub

How to sort Map by values in java 8?

Tuesday, February 2, 2021

Sorting HashMap by Value in Java 8 in Ascending and Descending Order

1. Overview

In this tutorial, We will learn how to sort HashMap by value using java 8 API

Most of the times, we do sort the hashmap based on the keys but not rather than its values. There are some scenarios for example HashMap stores the name as key and age as value. Now, we want to sort the customers based on the their value age.

Let us explore the techniques to do sort the values of hashmap in java 8.

Sorting HashMap by Value in Java 8 in Ascending and Descending Order



2. Sort HashMap By Value Java 8 - Ascending Order


Below example is to sort the map on values using Stream.sort() and Entry.comparingByValue() methods.

Entry.comparingByValue() does sorting in the ascending order.

Java 8 example:


package com.javaprogramto.collections.hashmap;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.Collectors;

public class SortHashMapByValues {

	public static void main(String[] args) {

		// creating HashMap
		Map<String, Integer> namesAges = new HashMap<>();

		// storing the values
		namesAges.put("Hari", 35);
		namesAges.put("Jhon", 30);
		namesAges.put("Jakey", 50);
		namesAges.put("kane", 45);

		Map<String, Integer> sortByValueMap = namesAges.entrySet().stream().sorted(Entry.comparingByValue())
				.collect(Collectors.toMap(entry -> entry.getKey(), entry -> entry.getValue(),
						(entry1, entry2) -> entry2, LinkedHashMap::new));

		System.out.println("HashMap before sorting by value - " + namesAges);
		System.out.println("HashMap after sorting by value - " + sortByValueMap);
	}

}
 
Output:
HashMap before sorting by value - {Hari=35, Jakey=50, Jhon=30, kane=45}
HashMap after sorting by value - {Jhon=30, Hari=35, kane=45, Jakey=50}
 
From the output, you can observe that new map is sorted based on the customer ages.

If you do not understand this java 8 lambda and stream operations, do not worry. I will explain you step by step and breaking down into separate statements.

Read the written comments for each line in the code and this will help you out for better understanding.

Once you are clear, you can write the code in single line.

package com.javaprogramto.collections.hashmap;

import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.stream.Collector;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class SortHashMapByValues {

	public static void main(String[] args) {

		// creating HashMap
		Map<String, Integer> namesAges = new HashMap<>();

		// storing the values
		namesAges.put("Hari", 35);
		namesAges.put("Jhon", 30);
		namesAges.put("Jakey", 50);
		namesAges.put("kane", 45);

		// Step 1: Getting the entry set from map
		Set<Map.Entry<String, Integer>> entrySet = namesAges.entrySet();

		// Step 2: converting entry set to stream
		Stream<Entry<String, Integer>> stream = entrySet.stream();

		// Step 3: comparator to sort using values.
		Comparator<Map.Entry<String, Integer>> comparator = Entry.comparingByValue();

		// Step 4: sorting the stream using comparator created in above step.
		Stream<Entry<String, Integer>> sortedStream = stream.sorted(comparator);

		// Step 5: Getting the each key and value from entry object from above stream.
		// Finally, adding each entry to the LinkedHashMap.
		// LinkedHashMap is used to preserve the insertion order. If you do not collect
		// object into LinkedHashMap then final sorted map looks like same as the
		// original map before sorting.
		Collector<Entry<String, Integer>, ?, Map<String, Integer>> toMap = Collectors.toMap(entry -> entry.getKey(),
				entry -> entry.getValue(), (entry1, entry2) -> entry2, LinkedHashMap::new);

		// Step 6: Collecting the sorted stream into Map.
		Map<String, Integer> finalSortedByValueMap = sortedStream.collect(toMap);

		// printing
		System.out.println("HashMap before sorting by value - " + namesAges);
		System.out.println("HashMap after sorting by value - " + finalSortedByValueMap);
	}
}

 
This program also generates the output as same as above single line stream example.

Note:
When you divide the stream into multiple lines, JVM does not execute the code immediately after executing the each line. All stream operations are invoked if and if only the terminal operations are called such as collect(), max(), min() methods.

3. Sort HashMap By Value Java 8 - Descending Order


Next, Learn how to sort the HashMap by values in Descending order using Collections.reverseOrder() method.

package com.javaprogramto.collections.hashmap;

import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.stream.Collector;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class SortHashMapByValues {

	public static void main(String[] args) {

		// creating HashMap
		Map<String, Integer> namesAges = new HashMap<>();

		// storing the values
		namesAges.put("Hari", 35);
		namesAges.put("Jhon", 30);
		namesAges.put("Jakey", 50);
		namesAges.put("kane", 45);

		Map<String, Integer> sortedMapInDescending = namesAges.entrySet()
			.stream()
			.sorted(Collections.reverseOrder(Entry.comparingByValue()))
			.collect(Collectors.toMap(entry -> entry.getKey(), entry -> entry.getValue(),
					(entry1, entry2) -> entry2, LinkedHashMap::new));
		
		// printing
		System.out.println("HashMap before sorting by value - " + namesAges);
		System.out.println("HashMap after sorting by value in descending order- " + sortedMapInDescending);
	}
}
 
Output:
HashMap before sorting by value - {Hari=35, Jakey=50, Jhon=30, kane=45}
HashMap after sorting by value in descending order- {Jakey=50, kane=45, Hari=35, Jhon=30}
 

4. HashMap Sorting using Method Reference


Example program using java 8 method ref concept.

// sorting using method ref
// Descending
Map<String, Integer> sortedMapInDescendingOrder = namesAges.entrySet()
.stream()
.sorted(Collections.reverseOrder(Entry.comparingByValue()))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
		(entry1, entry2) -> entry2, LinkedHashMap::new));

// Ascending
Map<String, Integer> sortedMapIAscendingOrder = namesAges.entrySet()
.stream()
.sorted(Collections.reverseOrder(Entry.comparingByValue()))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
	(entry1, entry2) -> entry2, LinkedHashMap::new));

 


5. Conclusion


In this article, We have seen how to sort HashMap by Value in Java 8 in descending or ascending order.

And alos seen using Method Reference concept.


Tuesday, January 26, 2021

Java TreeMap Vs HashMap With Examples

1. Overview

In this tutorial, We will learn the core differences between TreeMap and HashMap classes with example programs.

If you are new to java programming, suggest to go through the below topics.

HashMap Examples

TreeMap Examples

In java, All Map implementations are to store the key-value pairs but there are few differences based on the implementations.

Java TreeMap Vs HashMap With Examples


HashMap is extensively used in the day to day development from the collection framework when compared to TreeMap. Both uses internally bucketing concept but when any bucket partition becomes large the it does convert into TreeNode Structure.

2. Similarities between HashMap and TreeMap

The below are the common things in both classes. Let us look into those before understanding the differences.

2.1 HashMap and TreeMap classes implement Map<K,V>, Cloneable, Serializable interfaces and extends AbstractMap<K,V> class.

2.2 Both stores the values based on the keys. Always key and value should be provided.

2.3 Always key should be unique and if we add the same key again then old value will be replaced with the new value.

2.4 These are not synchronized.

2.5 Not thread-safe because if the original Map is modified during the iteration then it cause to throw runtime exception ConcurrentModificationException.

3. HashMap Examples

In the below example, we added few values to HashMap using put() method. Next, printed the all the values of HashMap.

Further tried to print the values using iterator and deleted the key "0333" from the original hashmap.

Removal key from hashmap produces the runtime exception.

package com.javaprogramto.collections.hashmap;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class HashMapExamples {

	public static void main(String[] args) {

		Map<String, String> hashMap = new HashMap<>();

		hashMap.put("0111", "one's");
		hashMap.put("0222", "two's");
		hashMap.put("0333", "three's");
		hashMap.put("0444", "four's");
		hashMap.put("0111", "one's modified");

		System.out.println("HashMap values are - " + hashMap);

		System.out.println("Iterating Hashmap and modifying the values");

		Set<String> keys = hashMap.keySet();

		Iterator<String> iterator = keys.iterator();

		while (iterator.hasNext()) {
			String key = iterator.next();
			System.out.println("key - " + key + ", value - " + hashMap.get(key));
			if (key == "0333") {
				hashMap.remove(key);
			}
		}

	}

}


Output:


HashMap values are - {0111=one's modified, 0222=two's, 0333=three's, 0444=four's}
Iterating Hashmap and modifying the values
key - 0111, value - one's modified
key - 0222, value - two's
key - 0333, value - three's
Exception in thread "main" java.util.ConcurrentModificationException
	at java.base/java.util.HashMap$HashIterator.nextNode(HashMap.java:1490)
	at java.base/java.util.HashMap$KeyIterator.next(HashMap.java:1513)
	at com.javaprogramto.collections.hashmap.HashMapExamples.main(HashMapExamples.java:29)


4. TreeMap Examples

In the below example, we added few values to TreeMap using put() method. Next, printed the all the values of TreeMap in sorted order.

Further tried to print the values using iterator and deleted the key "0333" from the original treemap.

Removal key from treemap produces the runtime exception.

package com.javaprogramto.collections.treemap;

import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

public class TreeMapExamples {

	public static void main(String[] args) {

		Map<String, String> treeMap = new TreeMap<>();

		treeMap.put("0111", "one's");
		treeMap.put("0222", "two's");
		treeMap.put("0333", "three's");
		treeMap.put("0444", "four's");
		treeMap.put("0111", "one's modified");

		System.out.println("treeMap values are - " + treeMap);

		System.out.println("Iterating treeMap and modifying the values");

		Set<String> keys = treeMap.keySet();

		Iterator<String> iterator = keys.iterator();

		while (iterator.hasNext()) {
			String key = iterator.next();
			System.out.println("key - " + key + ", value - " + treeMap.get(key));
			if (key == "0333") {
				treeMap.remove(key);
			}
		}

	}
}


Output:


treeMap values are - {0111=one's modified, 0222=two's, 0333=three's, 0444=four's}
Iterating treeMap and modifying the values
key - 0111, value - one's modified
key - 0222, value - two's
key - 0333, value - three's
Exception in thread "main" java.util.ConcurrentModificationException
	at java.base/java.util.TreeMap$PrivateEntryIterator.nextEntry(TreeMap.java:1208)
	at java.base/java.util.TreeMap$KeyIterator.next(TreeMap.java:1262)
	at com.javaprogramto.collections.treemap.TreeMapExamples.main(TreeMapExamples.java:29)

5. Differences between HashMap and TreeMap

The below are the main differences between these two maps.

5.1 TreeMap implements the NavigableMap interfaces rather than Map interface.

5.2 HashMap is implemented based on the hashtable

     TreeMap is implemented based on Tree Structured based map such as Red Black Tree which is a balanced.

5.3 HashMap allows only one null key and multiple null values.

      TreeMap does not allow null key but allows null values.

5.4 HashMap does not sort the keys where as TreeMap does sort the keys.

5.5 HashMap is faster then TreeMap because hashmap does not sort so it provides easy access to insertion and retrieval with constant time O(1) with put() and get() methods.

5.6 HashMap uses the equals() method for duplicate keys comparison but for TreeMap, keys are compared and sorted based on the compareTo() method. So, key must implement the Comparator or Comparable interface else will get the runtime error.

6. Conclusion

In this article, We've seen the first example programs on HashMap and TreeMap classes and next similarities and differences between HashMap and TreeMap.

GitHub HashMap

GitHub TreeMap

Java 8 Stream map() and filter() methods

Friday, January 22, 2021

How To Iterate or Traverse TreeMap In Reverse Order in Java?

1. Overview

In this tutorial, We will learn how to traverse and print the values of the TreeMap in the reverse order in java?

By default, TreeMap sorts the objects added to it in ascending order. But, now we want to print the values are in reverse order that means in the descending order. 

In the previous article, we have seen how to traverse TreeMap in natural order in java 8?

This can be done using the following in 3 ways.

1) Collections.reverseOrder()
2) TreeMap.descendingkeySet()
3) TreeMap.descendingMap()

How To Iterate or Traverse TreaMap In Reverse Order in Java?


2. TreeMap Reverse Traverse - Collections.reverseOrder()


First, let us learn the simple and easy one to understand the reversing and accessing the values from TreeMap.

When we create the TreeMap object, we just need to pass the Collections.reverseOrder() to the TreeMap constructor. Collections.reverseOrder() method indicates to TreeMap sort the keys based on the reverse order that is descending order.

The below example is based on the Collections.reverseOrder() method.

package com.javaprogramto.collections.treemap;

import java.util.Collections;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

public class TreeMapReverseTraversalExample {

	public static void main(String[] args) {
		
		// Creating the TreeMap object with reverse comparator using Collections.reverseOrder()
		Map<String, Integer> studentsCountMap = new TreeMap<>(Collections.reverseOrder());
		
		// Adding students class and no of students in the class
		studentsCountMap.put("2nd class", 200);
		studentsCountMap.put("1nd class", 100);
		studentsCountMap.put("4nd class", 400);
		studentsCountMap.put("5nd class", 500);
		studentsCountMap.put("3nd class", 300);
		
		// Getting the Set object using keySet() method which returns the keys in the reverse order
		Set<String> keysSet = studentsCountMap.keySet();
		
		// Getting the iterator object
		Iterator<String > it = keysSet.iterator();
		
		// Iterating the map using regular method of iterator which retrieves the values in the reverse order.
		while (it.hasNext()) {
			String key = it.next();
			System.out.println("Key - "+key+", Value - "+studentsCountMap.get(key));
		}
	}
}

Output:

See how the order of the output is printed in the reverse order.

Key - 5nd class, Value - 500
Key - 4nd class, Value - 400
Key - 3nd class, Value - 300
Key - 2nd class, Value - 200
Key - 1nd class, Value - 100

3. TreeMap Reverse Traverse - Collections. descendingkeySet()


The above method works only when we have control over creating the TreeMap instance otherwise need to follow the new method as below.

There are some scenarios where the TreeMap is created by another api or library that TreeMap object you are getting into your code.

In such cases, TreeMap has another method descendingkeySet() to get the keys in the descending order which is contrary to the natural order.

But, First need to get the keys in descending order and next get the value from map again with get() method.
import java.util.Collections;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeMap;

public class TreeMapReversedescendingkeySetExample {

	public static void main(String[] args) {
		
		// Creating the TreeMap object with default constructor
		TreeMap<String, Integer> studentsCountMap = new TreeMap<>();
		
		// Adding students class and no of students in the class
		studentsCountMap.put("2nd class", 200);
		studentsCountMap.put("1nd class", 100);
		studentsCountMap.put("4nd class", 400);
		studentsCountMap.put("5nd class", 500);
		studentsCountMap.put("3nd class", 300);
		
		// Getting all keys as Set object using descendingKeySet()
		Set<String> keysSet = studentsCountMap.descendingKeySet();
		
		// Getting the iterator object
		Iterator<String > it = keysSet.iterator();
		
		// Iterating the map using regular method of iterator which retrieves the values in the reverse order.
		while (it.hasNext()) {
			String key = it.next();
			System.out.println("Key - "+key+", Value - "+studentsCountMap.get(key));
		}
	}
}
Output:
Key - 5nd class, Value - 500
Key - 4nd class, Value - 400
Key - 3nd class, Value - 300
Key - 2nd class, Value - 200
Key - 1nd class, Value - 100

4. TreeMap Reverse Traverse - Collections. descendingMap()


Finally, TreeMap has another useful method to get the Map in descending order with descendingMap().

Next, iterate returned map with java 8 forEach() method to print the key-values

import java.util.Map;
import java.util.TreeMap;

public class TreeMapReversedescendingkeymapExample {

	public static void main(String[] args) {

		// Creating the TreeMap object with default constructor
		TreeMap<String, Integer> studentsCountMap = new TreeMap<>();

		// Adding students class and no of students in the class
		studentsCountMap.put("2nd class", 200);
		studentsCountMap.put("1nd class", 100);
		studentsCountMap.put("4nd class", 400);
		studentsCountMap.put("5nd class", 500);
		studentsCountMap.put("3nd class", 300);

		// Getting all keys as Set object using descendingKeySet()
		Map<String, Integer> map = studentsCountMap.descendingMap();

		map.forEach((key, value) -> System.out.println("Key - " + key + ", Value - " + value));
	}
}

5. Conclusion


In this article, we have explored the different ways to traverse the TreeMap in the reverse order.


Wednesday, January 20, 2021

How To Iterate TreeMap in older Java and new Java 8? Or How to iterate over each entry in a Java Map?

1. Overview

In this tutorial, We will learn how to iterate the map in older java versions and examples in java 8.

And alos let us explore how to iterate the keys of TreeMap sorted that means in the ascending order.

TreeMap can be used where we want the map sorted based on the key by default in the ascending or descending order use cases.

java 8 TreeMap Iterate Examples


2. Example to Iterate the TreeMap before JDK 8


In the below code we have created the TreeMap object and added few key value pairs. Here key is the type String and Value is type of Integer.


package com.javaprogramto.collections.treemap;

import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

public class TreeMapIterate {

	public static void main(String[] args) {
		
		// Creating the TreeMap object
		Map<String, Integer> studentsCountMap = new TreeMap<>();
		
		// Adding students class and no of students in the class
		studentsCountMap.put("2nd class", 200);
		studentsCountMap.put("1nd class", 100);
		studentsCountMap.put("4nd class", 400);
		studentsCountMap.put("5nd class", 500);
		studentsCountMap.put("3nd class", 300);
		
		// Getting the Set object using keySet() method
		Set<String> keysSet = studentsCountMap.keySet();
		
		// Getting the iterator object
		Iterator<String > it = keysSet.iterator();
		
		// Iterating the map using regular method of iterator.
		while (it.hasNext()) {
			String key = it.next();
			System.out.println("Key - "+key+", Value - "+studentsCountMap.get(key));
		}

	}

}

Output:

Key - 1nd class, Value - 100
Key - 2nd class, Value - 200
Key - 3nd class, Value - 300
Key - 4nd class, Value - 400
Key - 5nd class, Value - 500
In the above program, we have first got the all the keys of treemap using keySet() method and next used the iterator() method to get the Iterator instance.

Finally, used the traditional iterate method workflow to get the each key from iterator and passed the key to treemap to get the value of the corresponding key.

3. Java 8 Lamdba Foreach TreeMap


Next, Look at the below program to get the keys and values of TreeMap using Java 8 Lambda expressions with forEach() method.

package com.javaprogramto.collections.treemap;

import java.util.Map;
import java.util.TreeMap;

public class TreeMapIterateJava8 {

	public static void main(String[] args) {

		// Creating the TreeMap object
		Map<String, Integer> studentsCountMap = new TreeMap<>();

		// Adding students class and no of students in the class
		studentsCountMap.put("2nd class", 200);
		studentsCountMap.put("1nd class", 100);
		studentsCountMap.put("4nd class", 400);
		studentsCountMap.put("5nd class", 500);
		studentsCountMap.put("3nd class", 300);

		// Java 8 lambda foreach
		studentsCountMap.forEach((key, value) -> {
			System.out.println("Key - " + key + ", Value - " + value);
		});
	}
}
This ways also produces the same output as seen in the above section. This is the simplified version in java 8 and it internally uses the BiConsumer functional interface.


4. Java 8 Stream Foreach TreeMap EntrySet


Finally, explore the java 8 stream construct to get the Entry object from stream and pass it to forEach method.

package com.javaprogramto.collections.treemap;

import java.util.Map;
import java.util.TreeMap;

public class TreeMapIterateJava8 {

	public static void main(String[] args) {

		// Creating the TreeMap object
		Map<String, Integer> studentsCountMap = new TreeMap<>();

		// Adding students class and no of students in the class
		studentsCountMap.put("2nd class", 200);
		studentsCountMap.put("1nd class", 100);
		studentsCountMap.put("4nd class", 400);
		studentsCountMap.put("5nd class", 500);
		studentsCountMap.put("3nd class", 300);

		// java 8 Stream entry forEach
		studentsCountMap.entrySet().stream().forEach(
				entry -> System.out.println("entry key - " + entry.getKey() + ", entry value - " + entry.getValue()));
	}
}


Output:
entry key - 1nd class, entry value - 100
entry key - 2nd class, entry value - 200
entry key - 3nd class, entry value - 300
entry key - 4nd class, entry value - 400
entry key - 5nd class, entry value - 500

5. Conclusion


In this article, We have seen how to iterate the TreeMap in older and new JDK versions with examples.





Thursday, November 19, 2020

Min And Max Value From List In Java

1. Overview

In this tutorial, you'll learn what are the different ways to get the minimum and maximum value from unsorted List in java.

List may contains values type of integers or Strings or any custom objects. But let us understand with the simple data set such as list of integer values.


2. Using Sorting

First, sort the list using Collections.sort() in ascending order. Next, take the first value as min and last value as max.

package com.javaprogramto.java8.sorting.list;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class ListSortMinMaxExample {

	public static void main(String[] args) {

		// creating a list to store the integer values
		List<Integer> numbers = new ArrayList<>();

		// adding integer values
		numbers.add(30);
		numbers.add(20);
		numbers.add(50);
		numbers.add(10);
		numbers.add(20);

		// sorting List using collections.sort()
		Collections.sort(numbers);

		// getting the min value
		int min = numbers.get(0);

		// getting max value
		int max = numbers.get(numbers.size() - 1);

		System.out.println("List sorting - min : " + min + ", max : " + max);

	}

}

Output:

List sorting - min : 10, max : 50

3. Using Collections.min() and Collections.max() Methods

Java Collections class has two methods to get the min and max values using Collections.max() and Collections.min() methods.

import java.util.Collections;

public class ListCollectionsMinMaxExample {
	public static void main(String[] args) {

		// creating a list to store the integer values
		List<Integer> numbers = new ArrayList<>();

		// adding integer values
		numbers.add(23);
		numbers.add(45);
		numbers.add(76);
		numbers.add(9);
		numbers.add(10);

		// getting the min value using min() method 
		int min = Collections.min(numbers);

		// getting max value using max() method
		int max = Collections.max(numbers);

		System.out.println("List Collections api - min : " + min + ", max : " + max);
	}
}

Output:

List Collections api - min : 9, max : 76

4. Using Native Approach Method

First create the max variable with first value in the list. Next, Iterate the list values and compare the max value with the next value. When max value is greater than next number, store the current number in the max variable else do nothing. Next, Compare the max value with the next number in the list. Repeat the same logic.

At the end, whatever the value present in the max variable is the highest value.

The same logic applies to get the min value. But, condition should be min value less than current number.

package com.javaprogramto.java8.sorting.list;

import java.util.ArrayList;
import java.util.List;

public class ListNativeMinMaxExample {

	private static int getMinValue(List<Integer> numbers) {
		int min = Integer.MAX_VALUE;
		if (numbers.size() > 0) {

			for (Integer currentNumber : numbers) {

				if (min > currentNumber) {
					min = currentNumber;
				}
			}
		}
		return min;
	}

	private static int getMaxValue(List<Integer> numbers) {
		int max = Integer.MIN_VALUE;
		if (numbers.size() > 0) {

			for (Integer currentNumber : numbers) {

				if (max < currentNumber) {
					max = currentNumber;
				}
			}
		}
		return max;
	}

	public static void main(String[] args) {

		// creating a list to store the integer values
		List<Integer> numbers = new ArrayList<>();

		// adding integer values
		numbers.add(23);
		numbers.add(45);
		numbers.add(76);
		numbers.add(9);
		numbers.add(10);

		// getting the min value using min() method
		int min = getMinValue(numbers);

		// getting max value using max() method
		int max = getMaxValue(numbers);

		System.out.println("Native method - min : " + min + ", max : " + max);
	}

}

Output:

Native method - min : 9, max : 76

Time complexity is O(n).

5. Conclusion

In this article, you've seen the 3 different ways to get the min and max value from list in java.

GitHub

ListSortMinMaxExample

ListCollectionsMinMaxExample

ListNativeMinMaxExample

Read Next

Collections API

Collections.sort() and Custom Objects

How to find the largest value from array in java ?


Thursday, August 13, 2020

How To Convert ArrayList To String Array In Java 8 - toArray() Example

1. Overview

In this article, You're going to learn how to convert ArrayList to String[] Array in Java. ArrayList is used to store the List of String using the toArray() and Stream API toArray() method.

How To Convert ArrayList To String Array In Java 8 - toArray() Example

Wednesday, August 12, 2020

How to create a dictionary in Java - Java.util.Dictionary Examples

1. Overview

In this article, You will learn in-depth about the Dictionary class in java and how to create a dictionary in java?

Dictionary is an abstract class in java api which used in collections such as Hashtable. Dictionary supports backend to store the values as key, value pair. Key and Values are should be objects.

In Dictionary, Every key value must be having a value that can be a null or non-null object and keys are not stored in the insertion order. This does not allow duplicate keys.

Since the dictionary is an abstract class so, we can not create an object for it. Hence, object creation is possible to only its implementation classes. As a rule, the equals method should be used by implementations of this class to decide if two keys are the same.

How to create a dictionary in Java - Java.util.Dictionary Examples