Thursday, 26 December 2019

Get first element from a collection


Get first element from a list
Approach 1: Using index
int firstEle = list.get(0);

Approach 2: Using iterator
int firstEle = list.iterator().next();

Approach 3: Using stream
int firstEle = list.stream().findFirst().get();

App.java
package com.sample.app;

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

public class App {

	public static void main(String args[]) {
		List<Integer> list = Arrays.asList(2, 3, 5, 7);
		
		if(list.isEmpty()) {
			return;
		}
		
		int firstEle = list.get(0);
		firstEle = list.iterator().next();
		firstEle = list.stream().findFirst().get();
		
		
	}
}

Get first element from Queue
‘peek’ method is used to return first element in the queue.

Example
myQueue1.peek()


App.java
package com.sample.app;

import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;

public class App {

	public static void main(String args[]) {

		Queue<Integer> myQueue1 = new ConcurrentLinkedQueue<>();

		/* Add Elements to myQueue */
		myQueue1.add(10);
		myQueue1.add(20);
		myQueue1.add(30);
		myQueue1.add(40);
		myQueue1.add(50);

		System.out.println("Head Element " + myQueue1.peek() + " Retrieved from the Queue ");

	}
}

Output
Head Element 10 Retrieved from the Queue


For unordered collections like Set, since order is not preserved you can’t get the first element.

You may like

No comments:

Post a Comment