Java 8 – Find First and Last elements in an Arrays

In this article, we will discuss how to get First and Last elements from an Arrays using Java 8 Streams API

Find First and Last elements in an Arrays

  1. Using Java 8 Streams API
  2. Before Java 8 release

1. Using Java 8 Streams API

FindFirstAndLastElementInArrayListInJava8.java

package in.bench.resources.find.array;

import java.util.Arrays;

public class FindFirstAndLastElementInArrayListInJava8 {

	public static void main(String[] args) {

		// local variables
		String first = null;
		String last = null;


		// create String[] arrays
		String[] names = {
				"Deepinder Goyal",
				"Vinay Sanghi",
				"Bipin Preet Singh",
				"Vijay Shekhar Sharma",
				"Falguni Nayar"
		};


		// find First element in Arrays
		first = Arrays.stream(names).findFirst().get();


		// find Last element in Arrays
		last = Arrays.stream(names).reduce((one, two) -> two).get();


		// print to console
		System.out.println("First name in the Arrays is = " + first);
		System.out.println("Last name in the Arrays is = " + last);
	}
}

Output:

First name in the Arrays is = Deepinder Goyal
Last name in the Arrays is = Falguni Nayar

2. Before Java 8 Release

  • To find first and last elements in an Arrays, check whether Arrays length is greater-than zero
  • If Arrays length is greater-than zero, then
    • get first element using [index] position by passing 0th index
    • get last element using [index] position by passing last index of the Arrays i.e., [arr.length -1]

FindFirstAndLastElementInArrays.java

package in.bench.resources.find.array;

public class FindFirstAndLastElementInArrays {

	public static void main(String[] args) {

		// local variables
		String first = null;
		String last = null;


		// create String[] arrays
		String[] names = {
				"Deepinder Goyal",
				"Vinay Sanghi",
				"Bipin Preet Singh",
				"Vijay Shekhar Sharma",
				"Falguni Nayar"
		};


		// find first and last element in Arrays
		if(null != names && names.length > 0) {

			first = names[0];
			last = names[names.length - 1];
		}


		// print to console
		System.out.println("First name in the Arrays is = " + first);
		System.out.println("Last name in the Arrays is = " + last);
	}
}

Output:

First name in the Arrays is = Deepinder Goyal
Last name in the Arrays is = Falguni Nayar

References:

Happy Coding !!
Happy Learning !!

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