Java 8 – Find First and Last entries in a Map or HashMap

In this article, we will discuss how to get First and Last entries from a Map or HashMap using Java 8 Streams API

Find First and Last elements in HashMap

  1. Using Java 8 Streams API
  2. Before Java 8 release
    1. Using if-else statements while iterating
    2. Using ArrayList to store Map Keys
    3. Using Arrays to store Map Keys

1. Using Java 8 Streams API

FindFirstAndLastEntryInMapInJava8.java

package in.bench.resources.find.map;

import java.util.HashMap;
import java.util.Map;

public class FindFirstAndLastEntryInMapInJava8 {

	public static void main(String[] args) {

		// local variables
		Map.Entry<Integer, String> firstEntry = null, lastEntry = null;


		// create HashMap object
		Map<Integer, String> companies = new HashMap<>();


		// add entries to newly created HashMap
		companies.put(1, "Amazon");
		companies.put(2, "Microsoft");
		companies.put(3, "Google");
		companies.put(4, "Apple");
		companies.put(5, "Meta");


		// print all entries to console
		System.out.println("Map entries :- \n");
		companies.entrySet().stream().forEach(System.out::println);


		// find First entry in HashMap
		firstEntry = companies.entrySet().stream().findFirst().get();


		// find Last entry in HashMap
		lastEntry = companies.entrySet().stream().reduce((one, two) -> two).get();


		// print to console
		System.out.println("\n\nFirst entry in the Map is " + firstEntry);
		System.out.println("Last entry in the Map is " + lastEntry);
	}
}

Output:

Map entries :- 

1=Amazon
2=Microsoft
3=Google
4=Apple
5=Meta


First entry in the Map is 1=Amazon
Last entry in the Map is 5=Meta

2. Before Java 8 Release

2.1 Using if-else statements while iterating

  • Declare 2 local variables firstEntry and lastEntry
  • To find first and last entries in a HashMap, iterate through HashMap from beginning till the end
    • Check whether firstEntry is null, if it is null then set the first value as first entry
    • At the same time inside for-loop set iterating values to lastEntry variable and this way during last iteration of HashMaplast entry will be set to “lastEntry” variable
  • Finally, print First & Last entries to console

FindFirstAndLastEntryInMap.java

package in.bench.resources.find.map;

import java.util.HashMap;
import java.util.Map;

public class FindFirstAndLastEntryInMap {

	public static void main(String[] args) {

		// local variables
		Map.Entry<Integer, String> firstEntry = null, lastEntry = null;


		// create HashMap object
		Map<Integer, String> companies = new HashMap<>();


		// add entries to newly created HashMap
		companies.put(1, "Amazon");
		companies.put(2, "Microsoft");
		companies.put(3, "Google");
		companies.put(4, "Apple");
		companies.put(5, "Meta");


		// print all entries to console
		System.out.println("Map entries :- \n");


		// find first and last entries in HashMap
		for(Map.Entry<Integer, String> company : companies.entrySet()) {

			// print all entries to console
			System.out.println(company);


			// find first entry
			if(null == firstEntry) {
				firstEntry = company;
			}


			// find last entry
			lastEntry = company;
		}


		// print to console
		System.out.println("\n\nFirst entry in the Map is " + firstEntry);
		System.out.println("Last entry in the Map is " + lastEntry);
	}
}

Output:

Map entries :- 

1=Amazon
2=Microsoft
3=Google
4=Apple
5=Meta


First entry in the Map is 1=Amazon
Last entry in the Map is 5=Meta

2.2 Using ArrayList to store Map Keys

  • Declare 2 local variables firstEntry and lastEntry of String-type
  • To find first and last entries in a HashMap, create a new ArrayList of Integer-type to store Map Keys
  • Check the newly created ArrayList of Key Set and if it is not empty, then
    • get first key & value (entry) using get(index) method by passing 0th index
    • get last key & value (entry) using get(index) method by passing last index of the list i.e., (list.size -1)
  • Finally, print First & Last entries to console

FindFirstAndLastEntryInMapUsingList.java

package in.bench.resources.find.map;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class FindFirstAndLastEntryInMapUsingList {

	public static void main(String[] args) {

		// local variables
		String firstEntry = null, lastEntry = null;


		// create HashMap object
		Map<Integer, String> companies = new HashMap<>();


		// add entries to newly created HashMap
		companies.put(1, "Amazon");
		companies.put(2, "Microsoft");
		companies.put(3, "Google");
		companies.put(4, "Apple");
		companies.put(5, "Meta");


		// print all entries to console
		System.out.println("Map entries :- \n");
		for(Map.Entry<Integer, String> company : companies.entrySet()) {
			System.out.println(company);
		}


		// convert keySet into ArrayList
		List<Integer> ranks = new ArrayList<Integer>(companies.keySet());


		// get firstEntry & lastEntry
		if(!ranks.isEmpty() && ranks.size() > 0) {

			// find first entry
			firstEntry = ranks.get(0) + "=" + companies.get(ranks.get(0));


			// find last entry
			lastEntry = ranks.get(ranks.size() - 1) + "=" 
					+ companies.get(ranks.get(ranks.size() - 1));
		}


		// print to console
		System.out.println("\n\nFirst entry in the Map is " + firstEntry);
		System.out.println("Last entry in the Map is " + lastEntry);

	}
}

Output:

Map entries :- 

1=Amazon
2=Microsoft
3=Google
4=Apple
5=Meta


First entry in the Map is 1=Amazon
Last entry in the Map is 5=Meta

2.3 Using Arrays to store Map Keys

  • Declare 2 local variables firstEntry and lastEntry of String-type
  • To find first and last entries in a HashMap, create a new Arrays of Integer-type to store Map Keys
  • Check the newly created Arrays of Key Set and if it is not null and length is greater than zero, then
    • get first key & value (entry) using [index] position by passing 0th index
    • get last key & value (entry) using [index] position by passing last index of the Arrays i.e., [arr.length -1]
  • Finally, print First & Last entries to console

FindFirstAndLastEntryInMapUsingArrays.java

package in.bench.resources.find.map;

import java.util.HashMap;
import java.util.Map;

public class FindFirstAndLastEntryInMapUsingArrays {

	public static void main(String[] args) {

		// local variables
		String firstEntry = null, lastEntry = null;


		// create HashMap object
		Map<Integer, String> companies = new HashMap<>();


		// add entries to newly created HashMap
		companies.put(1, "Amazon");
		companies.put(2, "Microsoft");
		companies.put(3, "Google");
		companies.put(4, "Apple");
		companies.put(5, "Meta");


		// print all entries to console
		System.out.println("Map entries :- \n");
		for(Map.Entry<Integer, String> company : companies.entrySet()) {
			System.out.println(company);
		}


		// convert keySet into Arrays
		Integer[] ranks = companies.keySet().toArray(new Integer[companies.size()]);


		// get firstEntry & lastEntry
		if(null != ranks && ranks.length > 0) {

			// find first entry
			firstEntry = ranks[0] + "=" + companies.get(ranks[0]);


			// find last entry
			lastEntry = ranks[ranks.length - 1] + "=" 
					+ companies.get(ranks[ranks.length - 1]);
		}


		// print to console
		System.out.println("\n\nFirst entry in the Map is " + firstEntry);
		System.out.println("Last entry in the Map is " + lastEntry);

	}
}

Output:

Map entries :- 

1=Amazon
2=Microsoft
3=Google
4=Apple
5=Meta


First entry in the Map is 1=Amazon
Last entry in the Map is 5=Meta

References:

Happy Coding !!
Happy Learning !!

Java 8 – Find First and Last elements in a Set or HashSet