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 :
- Using Java 8 Streams API
- Before Java 8 release
- Using if-else statements while iterating
- Using ArrayList to store Map Keys
- Using Arrays to store Map Keys
1. Using Java 8 Streams API :
- To find first entry in a HashMap, we can use findFirst() method of Stream API which returns Optional<T> and
- We can invoke get() method on Optional<T> to obtain the final result
- Similarly, to get last element from HashMap, we can use reduce() method of Stream API which returns Optional<T> and
- We can invoke get() method on Optional<T> to obtain the final result
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 HashMap, last 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
Related Articles:
- Java 8 – Find Largest number in an Arrays or List or Stream
- Java 8 – Find Smallest number in an Arrays or List or Stream
- Java 8 – Find 2nd Largest number in an Arrays or List or Stream
- Java 8 – Find 2nd Smallest number in an Arrays or List or Stream
- Java 8 – Find sum of Largest 2 numbers in an Arrays or List or Stream
- Java 8 – Find sum of Smallest 2 numbers in an Arrays or List or Stream
- Java 8 – Find 1st and Last elements in an Arrays
- Java 8 – Find 1st and Last elements in a List or ArrayList
- Java 8 – Find 1st and Last elements in a Set or HashSet
- Java 8 – Find 1st and Last entries in a Map or HashMap
- Java 8 – Find sum and average of a List or ArrayList
- Java 8 – How to calculate sum and average of an Arrays ?
References:
- https://docs.oracle.com/javase/8/docs/api/java/util/Map.html
- https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html
- https://docs.oracle.com/javase/8/docs/api/java/util/Arrays.html
- https://docs.oracle.com/javase/8/docs/api/java/util/List.html
- https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html
- https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html
- https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#findFirst–
- https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#reduce-java.util.function.BinaryOperator-
- https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html
- https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html#get–
Happy Coding !!
Happy Learning !!