Java collection get one element

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

Источник

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: 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 8 : Find first element from a collection (List or Set)

sneppets-java8

This tutorial explains you how to find first element from collection like List or Set using Java 8 streams findFirst(), iterator() and listIterator methods.

Find first element from List or Set

The below example shows how to get first element of List or Set using different methods of List or Set.

package com.Sneppets.app; import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import com.plan.domain.Skill; public class FirstElementCollectionExample < public static void main (String[] args) < //List ListskillList = new ArrayList<>(); skillList.add(new Skill(1L, "Java")); skillList.add(new Skill(2L, "Python")); skillList.add(new Skill(3L, "Golang")); skillList.add(new Skill(4L, "C++")); //Set Set skillSet = new LinkedHashSet<>(); skillSet.add(new Skill(1L, "Java")); skillSet.add(new Skill(2L, "Python")); skillSet.add(new Skill(3L, "Golang")); skillSet.add(new Skill(4L, "C++")); //using Java 8 streams findFirst() method String firstSkillNameinList = null; if (skillList.stream().findFirst().isPresent()) < firstSkillNameinList = skillList.stream().findFirst().get().getName(); >System.out.println("Java 8: First skill name of Skill List : " + firstSkillNameinList); String firstSkillNameinSet = null; if(skillSet.stream().findFirst().isPresent()) < firstSkillNameinSet = skillSet.stream().findFirst().get().getName(); >System.out.println("Java 8:First skill name of Skill Set : " + firstSkillNameinSet); //using list get(index) method String firstSkillNamel = null; if(!skillList.isEmpty()) < firstSkillNamel = skillList.get(0).getName(); >System.out.println("List get(index) method : First skill name of Skill List : " + firstSkillNamel); //using set iterator() method String firstSkillNames = null; if(!skillSet.isEmpty()) < firstSkillNames = skillSet.iterator().next().getName(); >System.out.println("Set iterator() method : First skill name of Skill Set : " + firstSkillNames); //using listIterator() method String firstSkillNamel1 = null; if(!skillList.isEmpty()) < firstSkillNamel1 = skillList.listIterator().next().getName(); >System.out.println("List listIterator() method : First skill name of Skill List : " + firstSkillNamel1); > >
Java 8: First skill name of Skill List : Java Java 8:First skill name of Skill Set : Java List get(index) method : First skill name of Skill List : Java Set iterator() method : First skill name of Skill Set : Java List listIterator() method : First skill name of Skill List : Java

java.util.Stream

A stream provides an interface to a sequenced set of values of a specific element type. However, stream consumes data from the source such as Collection List or Set as shown in the example above. Note, Collection.stream() creates as sequential stream and Collection.parallelStream() creates a parallel stream.

We chose Collection.stream() in our example and use findFirst() method to identify first element of a Collection. This method returns an Optional first element of the sequential stream or an empty Optional if the stream is empty.

You can also use java.util.Optional.isPresent() to check if there is a first element present in the collection using Collection.stream.findFirst().isPresent() as shown above.

Further Reading

References

Источник

Читайте также:  Read php books online
Оцените статью