Java collection get first

Get first element in list

This example will show how to get the first element in a collection. While this may seem trivial, utilities exist to provide a more readable, eloquent approach vs the solution outlined in the straight up java section.

Straight up Java

This snippet will get the first element in a collection using java. It will check if the ArrayList is empty and if the size is greater than 0. It then will return the first element by getting the first element in the list.

@Test public void get_first_element_in_list_with_java ()  ListString> strings = new ArrayListString>(); strings.add("one"); strings.add("two"); strings.add("three"); String firstElement = null; if (!strings.isEmpty() && strings.size() > 0)  firstElement = strings.get(0); > assertEquals("one", firstElement); >

Java 8

This snippet will find the first element in arraylist using java 8. The Java 8 Streams API provides Streams.findFirst which will return the wrapper Optional object describing the first element of the stream. If the arraylist is empty, an empty Optional will be returned.

@Test public void get_first_element_in_list_with_java8 ()  ListString> strings = new ArrayListString>(); strings.add("one"); strings.add("two"); strings.add("three"); OptionalString> firstElement = strings.stream().findFirst(); assertEquals("one", firstElement.orElse("two")); >

Google Guava

Guava Iterables.getFirst will return the first element in the list or the default value if the list is empty.

@Test public void get_first_element_in_list_with_guava ()  ListString> strings = Lists.newArrayList("one", "two", "three"); String firstElement = Iterables.getFirst(strings, null); assertEquals("one", firstElement); >

Apache Commons

Apache commons CollectionUtils.get will return the element at the specified index.

@Test public void get_first_element_in_list_with_apachecommons ()  ListString> strings = Lists.newArrayList("one", "two", "three"); String firstElement = (String) CollectionUtils.get(strings, 0); assertEquals("one", firstElement); >

Get first element in list posted by Justin Musgrove on 31 January 2014

Tagged: java and java-collections

Источник

Java: Get first item from a collection

To get the first item from a collection in Java, you can use the iterator() method to get an iterator for the collection, and then call the next() method on the iterator to get the first element.

For example, suppose you have a List of strings called myList and you want to get the first element:

List myList = . ; Iterator iterator = myList.iterator(); if (iterator.hasNext()) < String firstElement = iterator.next(); // do something with the first element >

Alternatively, you can use the get(int index) method to get the element at a specific index in a List , or the first() method to get the first element in a Set .

List myList = . ; String firstElement = myList.get(0); Set mySet = . ; String firstElement = mySet.first();

Note that these methods will throw an exception if the collection is empty, so you should make sure to check the size of the collection before attempting to get the first element.

I hope this helps. Let me know if you have any questions.

BookDuck

  • Is Java «pass-by-reference» or «pass-by-value»?
  • How do I read / convert an InputStream into a String in Java?
  • Avoiding NullPointerException in Java
  • What are the differences between a HashMap and a Hashtable in Java?
  • How do I generate random integers within a specific range in Java?
  • How do I efficiently iterate over each entry in a Java Map?
  • How can I create a memory leak in Java?
  • When to use LinkedList over ArrayList in Java?
  • Does a finally block always get executed in Java?
  • How to get an enum value from a string value in Java
  • How to get the first element of the List or Set?

Источник

Java: Get first item from a collection

If I have a collection, such as Collection strs , how can I get the first item out? I could just call an Iterator , take its first next() , then throw the Iterator away. Is there a less wasteful way to do it?

Java Solutions

Solution 1 — Java

Looks like that is the best way to do it:

String first = strs.iterator().next(); 

Great question. At first, it seems like an oversight for the Collection interface.

Note that «first» won’t always return the first thing you put in the collection, and may only make sense for ordered collections. Maybe that is why there isn’t a get(item) call, since the order isn’t necessarily preserved.

While it might seem a bit wasteful, it might not be as bad as you think. The Iterator really just contains indexing information into the collection, not a usually a copy of the entire collection. Invoking this method does instantiate the Iterator object, but that is really the only overhead (not like copying all the elements).

For example, looking at the type returned by the ArrayList.iterator() method, we see that it is ArrayList::Itr . This is an internal class that just accesses the elements of the list directly, rather than copying them.

Just be sure you check the return of iterator() since it may be empty or null depending on the implementation.

Solution 2 — Java

Because really, if you’re using Collections, you should be using Google Collections.

Solution 3 — Java

Optional firstElement = collection.stream().findFirst(); 

For older versions of java, there is a getFirst method in Guava Iterables:

Iterables.getFirst(iterable, defaultValue) 

Solution 4 — Java

There is no such a thing as «first» item in a Collection because it is .. well simply a collection.

From the Java doc’s Collection.iterator() method:

>There are no guarantees concerning the order in which the elements are returned.

If you use another interface such as List, you can do the following:

But directly from a Collection this is not possible.

Solution 5 — Java

It sounds like your Collection wants to be List-like, so I’d suggest:

List myList = new ArrayList(); . String first = myList.get(0); 

Solution 6 — Java

public static Optional findFirst(List result) < return Optional.ofNullable(result) .map(List::stream) .flatMap(Stream::findFirst); > 

above code snippet preserve from NullPointerException and IndexOutOfBoundsException

Solution 7 — Java

In Java 8 you have some many operators to use, for instance limit

 /** * Operator that limit the total number of items emitted through the pipeline * Shall print * [1] * @throws InterruptedException */ @Test public void limitStream() throws InterruptedException < Listlist = Arrays.asList(1, 2, 3, 1, 4, 2, 3) .stream() .limit(1) .collect(toList()); System.out.println(list); > 

Solution 8 — Java

Guava provides an onlyElement Collector , but only use it if you expect the collection to have exactly one element.

Collection stringCollection = . ; String string = collection.stream().collect(MoreCollectors.onlyElement()) 

If you are unsure of how many elements there are, use findFirst .

Optional optionalString = collection.stream().findFirst(); 

Solution 9 — Java

You can do a casting. For example, if exists one method with this definition, and you know that this method is returning a List:

CollectionString> getStrings(); 

And after invoke it, you need the first element, you can do it like this:

List listString = (List) getStrings(); String firstElement = (listString.isEmpty() ? null : listString.get(0)); 

Solution 10 — Java

If you are using Apache Commons Collections 4 there is an IterableUtils.first method. It contains an optimization in the case of List s and is neat to use. It’s very similar to the Guava method. The code would look like

String firstStr = IterableUtils.first(strs); 

Solution 11 — Java

If you know that the collection is a queue then you can cast the collection to a queue and get it easily.

There are several structures you can use to get the order, but you will need to cast to it.

Solution 12 — Java

It totally depends upon which implementation you have used, whether arraylist linkedlist, or other implementations of set.

if it is set then you can directly get the first element , their can be trick loop over the collection , create a variable of value 1 and get value when flag value is 1 after that break that loop.

if it is list’s implementation then it is easy by defining index number.

Solution 13 — Java

strs.isEmpty() ? "" : strs.iterator().next(); 

Solution 14 — Java

String strz[] = strs.toArray(String[strs.size()]); String theFirstOne = strz[0]; 

The javadoc for Collection gives the following caveat wrt ordering of the elements of the array:

> If this collection makes any guarantees as to what order its elements are returned by its iterator, this method must return the elements in the same order.

Источник

How to get the first element of the List in Java?

The List interface extends Collection interface. It is a collection that stores a sequence of elements. ArrayList is the most popular implementation of the List interface. User of a list has quite precise control over where an element to be inserted in the List. These elements are accessible by their index and are searchable.

List interface provides a get() method to get the element at particular index. You can specify index as 0 to get the first element of the List. In this article, we’re exploring get() method usage via multiple examples.

Syntax

Returns the element at the specified position.

Parameters

Returns

The element at the specified position.

Throws

Example 1

Following is the example showing how to get the first element from a List.

package com.tutorialspoint; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class CollectionsDemo < public static void main(String[] args) < Listlist = new ArrayList<>(Arrays.asList(4,5,6)); System.out.println("List: " + list); // First element of the List System.out.println("First element of the List: " + list.get(0)); > >

Output

This will produce the following result −

List: [4, 5, 6] First element of the List: 4

Example 2

Following is the example where getting the first element from a List can throw an exception.

package com.tutorialspoint; import java.util.ArrayList; import java.util.List; public class CollectionsDemo < public static void main(String[] args) < Listlist = new ArrayList<>(); System.out.println("List: " + list); try < // First element of the List System.out.println("First element of the List: " + list.get(0)); >catch(Exception e) < e.printStackTrace(); >> >

Output

This will produce the following result −

List: [] java.lang.IndexOutOfBoundsException: Index: 0, Size: 0 at java.util.ArrayList.rangeCheck(ArrayList.java:659) at java.util.ArrayList.get(ArrayList.java:435) at com.tutorialspoint.CollectionsDemo.main(CollectionsDemo.java:11)

Источник

Читайте также:  Java method catch exception
Оцените статью