Get last element of set java

[java] Java get last element of a collection

I have a collection, I want to get the last element of the collection. What’s the most straighforward and fast way to do so?

One solution is to first toArray(), and then return the last element of the array. Is there any other better ones?

This question is related to java collections iterator

The answer is

A Collection is not a necessarily ordered set of elements so there may not be a concept of the «last» element. If you want something that’s ordered, you can use a SortedSet which has a last() method. Or you can use a List and call mylist.get(mylist.size()-1);

If you really need the last element you should use a List or a SortedSet . But if all you have is a Collection and you really, really, really need the last element, you could use toArray() or you could use an Iterator and iterate to the end of the list.

public Object getLastElement(final Collection c) < final Iterator itr = c.iterator(); Object lastElement = itr.next(); while(itr.hasNext()) < lastElement = itr.next(); >return lastElement; > 

Iterables.getLast from Google Guava. It has some optimization for List s and SortedSet s too.

Читайте также:  Параметры функции range python

Well one solution could be:

Edit: You have to convert the collection to a list before maybe like this: new ArrayList(coll)

A reasonable solution would be to use an iterator if you don’t know anything about the underlying Collection, but do know that there is a «last» element. This isn’t always the case, not all Collections are ordered.

Object lastElement = null; for (Iterator collectionItr = c.iterator(); collectionItr.hasNext(); )

This should work without converting to List/Array:

collectionName.stream().reduce((prev, next) -> next).orElse(null) 

There isn’t a last() or first() method in a Collection interface. For getting the last method, you can either do get(size() — 1) on a List or reverse the List and do get(0) . I don’t see a need to have last() method in any Collection API unless you are dealing with Stacks or Queues

If you have Iterable convert to stream and find last element

 Iterator sourceIterator = Arrays.asList("one", "two", "three").iterator(); Iterable iterable = () -> sourceIterator; String last = StreamSupport.stream(iterable.spliterator(), false).reduce((first, second) -> second).orElse(null); 

Or you can use a for-each loop:

Collection items = . ; X last = null; for (X x : items) last = x; 

To avoid some of the problems mentioned above (not robust for nulls etc etc), to get first and last element in a list an approach could be

import java.util.List; public static final A getLastElement(List list) < return list != null ? getElement(list, list.size() - 1) : null; >public static final A getFirstElement(List list) < return list != null ? getElement(list, 0) : null; >private static final A getElement(List list, int pointer) < A res = null; if (list.size() >0) < res = list.get(pointer); >return res; > 

The convention adopted is that the first/last element of an empty list is null.

Источник

Get the first and last elements of the Set or HashSet in Java [2 ways]

In this post, I will be sharing how to get the first and last elements of the Set or HashSet in Java with examples. There are two ways to achieve our goal:

Let’s dive deep into the topic:

Get the first and last element of the Set or HashSet

1. Using Stream API

We can easily get the first element of the Set(or HashSet) using the findFirst() method of Stream API that returns Optional and we can invoke the get() method on Optional to obtain the final result as shown below in the example.

To get the last element of the Set(or HashSet), we can use Stream API reduce() method that returns Optional. We will invoke the get() method on Optional to obtain the final result as shown below in the example.

import java.util.Set; import java.util.HashSet; public class FirstLastElementSet public static void main(String args[])  String firstElement = null; String lastElement = null; // Creating object of HashSet SetString> brands = new HashSet<>(); brands.add("Apple"); brands.add("Amazon"); brands.add("Google"); brands.add("Oracle"); // Printing the Original HashSet elements System.out.println(brands); // Getting first element firstElement = brands.stream().findFirst().get(); System.out.println("First element is: "+ firstElement); // Getting last element lastElement = brands.stream().reduce((first, second) -> second).get(); System.out.println("Last element is: "+ lastElement); > > 

Output:
[Google, Apple, Amazon, Oracle]
First element is: Google
Last element is: Oracle

2. Using an iterator

Using an iterator also, we can find the first and last elements of the Set or HashSet in Java as shown below in the example:

To get the first element just use set.iterator().next() whereas to get the last element just iterate the HashSet object from the beginning till the end.

import java.util.Set; import java.util.HashSet; import java.util.Iterator; public class FirstLastElementSet2  public static void main(String args[])  String firstSetElement = null; String lastSetElement = null; // Creating object of HashSet class SetString> currencies = new HashSet<>(); currencies.add("Rupee"); currencies.add("Dollar"); currencies.add("Pound"); currencies.add("Yen"); // Printing the Original HashSet elements System.out.println(currencies); // Getting first element if (!currencies.isEmpty())  firstSetElement = currencies.iterator().next(); > System.out.println("First element is: "+ firstSetElement); // Getting last element IteratorString> iterator = currencies.iterator(); while(iterator.hasNext())  lastSetElement = iterator.next(); > System.out.println("Last element is: "+ lastSetElement); > > 

Output:
[Yen, Dollar, Rupee, Pound]
First element is: Yen
Last element is: Pound

That’s all for today. Please mention in the comments if you have any questions related to how to get the first and last elements of the Set or HashSet in Java with examples.

About The Author

Subham Mittal has worked in Oracle for 3 years.
Enjoyed this post? Never miss out on future posts by subscribing JavaHungry

Источник

Java get last element of a collection

This method will throw a if the list is empty, as opposed to an , as with the typical approach — I find a much nicer, or the ability to specify a default: You can also provide a default value if the list is empty, instead of an exception: or, if you’re using Options: Solution 3: this should do it: Solution 4: I use micro-util class for getting last (and first) element of list: Slightly more flexible: Solution 1: A is not a necessarily ordered set of elements so there may not be a concept of the «last» element.

Java get last element of a collection

I have a collection, I want to get the last element of the collection. What’s the most straighforward and fast way to do so?

One solution is to first toArray(), and then return the last element of the array. Is there any other better ones?

A Collection is not a necessarily ordered set of elements so there may not be a concept of the «last» element. If you want something that’s ordered, you can use a SortedSet which has a last() method. Or you can use a List and call mylist.get(mylist.size()-1);

If you really need the last element you should use a List or a SortedSet . But if all you have is a Collection and you really, really, really need the last element, you could use toArray() or you could use an Iterator and iterate to the end of the list.

public Object getLastElement(final Collection c) < final Iterator itr = c.iterator(); Object lastElement = itr.next(); while(itr.hasNext()) < lastElement = itr.next(); >return lastElement; > 

Iterables.getLast from Google Guava . It has some optimization for List s and SortedSet s too.

It is not very efficient solution, but working one:

public static T getFirstElement(final Iterable elements) < return elements.iterator().next(); >public static T getLastElement(final Iterable elements) < T lastElement = null; for (T element : elements) < lastElement = element; >return lastElement; > 

This should work without converting to List/Array:

collectionName.stream().reduce((prev, next) -> next).orElse(null) 

How to get first and last element in an array in java?, Thats right you might have declared an array to hold 25 items, But you may have filled only 10. so (array.length-1) will still give you the index of the 25th item, not the last item you filled in i.e actually in the 10th position or 9th index!

Get last X items of a list in java

I can only seem to find answers about last/first element in a list or that you can get a specific item etc.

Lets say I have a list of 100 elements, and I want to return the last 40 elements. How do I do that? I tried doing this but it gave me one element..

Post last40posts = posts.get(posts.size() -40); 

Do use the method sub list

List myLastPosts = posts.subList(posts.size()-40, posts.size()); 

(To complete Ankit Malpani answer) If 40 is provided by our lovely users, then you will have to restrict it to the list size:

posts.subList(posts.size()-Math.min(posts.size(),40), posts.size()) 
@Test public void should_extract_last_n_entries() < ListmyList = Arrays.asList("0","1","2","3","4"); int myListSize = myList.size(); log.info(myList.subList(myListSize,myListSize).toString()); // output : [] log.info(myList.subList(myListSize-2,myListSize).toString()); // output : [3, 4] log.info(myList.subList(myListSize-5,myListSize).toString()); // output : [0, 1, 2, 3, 4] int lastNEntries = 50; // now use user provided int log.info(myList.subList(myListSize-Math.min(myListSize,lastNEntries),myListSize).toString()); // output : [0, 1, 2, 3, 4] // log.info(myList.subList(myListSize-lastNEntries,myListSize).toString()); // ouch IndexOutOfBoundsException: fromIndex = -45 > 

Your code will give you only a single element. You need to use subList method like:

posts.subList(posts.size()-40, posts.size()) 

Find the last element of a Stream in Java, To get the last element, you can use the skip () method along with count () method. Stream.skip (stream.count ()-1) This returns a stream after removing first size ()-1 elements, which results in single element stream. This method is followed by findFirst () method, which return the first element which is …

How to get the last value of an ArrayList

How can I get the last value of an ArrayList?

The following is part of the List interface (which ArrayList implements):

E is the element type. If the list is empty, get throws an IndexOutOfBoundsException . You can find the whole API documentation here.

There isn’t an elegant way in vanilla Java.

Google Guava

The Google Guava library is great — check out their Iterables class. This method will throw a NoSuchElementException if the list is empty, as opposed to an IndexOutOfBoundsException , as with the typical size()-1 approach — I find a NoSuchElementException much nicer, or the ability to specify a default:

lastElement = Iterables.getLast(iterableList); 

You can also provide a default value if the list is empty, instead of an exception:

lastElement = Iterables.getLast(iterableList, null); 

or, if you’re using Options:

lastElementRaw = Iterables.getLast(iterableList, null); lastElement = (lastElementRaw == null) ? Option.none() : Option.some(lastElementRaw); 
if (arrayList != null && !arrayList.isEmpty())

I use micro-util class for getting last (and first) element of list:

public final class Lists < private Lists() < >public static T getFirst(List list) < return list != null && !list.isEmpty() ? list.get(0) : null; >public static T getLast(List list) < return list != null && !list.isEmpty() ? list.get(list.size() - 1) : null; >> 
import java.util.List; /** * Convenience class that provides a clearer API for obtaining list elements. */ public final class Lists < private Lists() < >/** * Returns the first item in the given list, or null if not found. * * @param The generic list type. * @param list The list that may have a first item. * * @return null if the list is null or there is no first item. */ public static T getFirst( final List list ) < return getFirst( list, null ); >/** * Returns the last item in the given list, or null if not found. * * @param The generic list type. * @param list The list that may have a last item. * * @return null if the list is null or there is no last item. */ public static T getLast( final List list ) < return getLast( list, null ); >/** * Returns the first item in the given list, or t if not found. * * @param The generic list type. * @param list The list that may have a first item. * @param t The default return value. * * @return null if the list is null or there is no first item. */ public static T getFirst( final List list, final T t ) < return isEmpty( list ) ? t : list.get( 0 ); >/** * Returns the last item in the given list, or t if not found. * * @param The generic list type. * @param list The list that may have a last item. * @param t The default return value. * * @return null if the list is null or there is no last item. */ public static T getLast( final List list, final T t ) < return isEmpty( list ) ? t : list.get( list.size() - 1 ); >/** * Returns true if the given list is null or empty. * * @param The generic list type. * @param list The list that has a last item. * * @return true The list is empty. */ public static boolean isEmpty( final List list ) < return list == null || list.isEmpty(); >> 

Java Program to Get the First and the Last Element of a, A linked list is a linear data structure, in which the elements are not stored at contiguous memory locations. The given task is to retrieve the first and the last element of a given linked list. Properties of a Linked List: Elements are stored in a non-contiguous manner. Every element is an object which contains a …

Источник

Оцените статью