Array List의 마지막 값을 얻는 방법
Array List의 마지막 값을 얻으려면 어떻게 해야 합니까?
다음은 (ArrayList가 구현한) 인터페이스의 일부입니다.
E e = list.get(list.size() - 1);
E
는 요소 유형입니다.비어 있는 는, 「」를 해 주세요.get
는 를 슬로우합니다.API 매뉴얼은 여기를 참조해 주세요.
바닐라 자바에는 우아한 방법이 없다.
구글 구아바
Google Guava 라이브러리는 훌륭합니다.클래스를 확인해 주세요.이 메서드는 목록이 비어 있는 경우 일반적인 것과 같이가 아닌 를 슬로우합니다.size()-1
- 접근권을 .NoSuchElementException
또는 기본값을 지정하는 기능이 있습니다.
lastElement = Iterables.getLast(iterableList);
목록이 비어 있는 경우 예외 대신 기본값을 지정할 수도 있습니다.
lastElement = Iterables.getLast(iterableList, null);
또는 옵션을 사용하는 경우:
lastElementRaw = Iterables.getLast(iterableList, null);
lastElement = (lastElementRaw == null) ? Option.none() : Option.some(lastElementRaw);
이것으로 충분합니다.
if (arrayList != null && !arrayList.isEmpty()) {
T item = arrayList.get(arrayList.size()-1);
}
목록의 마지막(및 첫 번째) 요소를 얻기 위해 micro-util 클래스를 사용합니다.
public final class Lists {
private Lists() {
}
public static <T> T getFirst(List<T> list) {
return list != null && !list.isEmpty() ? list.get(0) : null;
}
public static <T> T getLast(List<T> 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 <T> 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> T getFirst( final List<T> list ) {
return getFirst( list, null );
}
/**
* Returns the last item in the given list, or null if not found.
*
* @param <T> 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> T getLast( final List<T> list ) {
return getLast( list, null );
}
/**
* Returns the first item in the given list, or t if not found.
*
* @param <T> 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> T getFirst( final List<T> 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 <T> 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> T getLast( final List<T> list, final T t ) {
return isEmpty( list ) ? t : list.get( list.size() - 1 );
}
/**
* Returns true if the given list is null or empty.
*
* @param <T> The generic list type.
* @param list The list that has a last item.
*
* @return true The list is empty.
*/
public static <T> boolean isEmpty( final List<T> list ) {
return list == null || list.isEmpty();
}
}
size()
method ArrayList 내의 합니다.요소의 인덱스 값은 다음과 같습니다.0
through를 통해.(size()-1)
해서 이렇게 쓸 수 있어요.myArrayList.get(myArrayList.size()-1)
마지막 요소를 가져옵니다.
람다 사용:
Function<ArrayList<T>, T> getLast = a -> a.get(a.size() - 1);
Java에서 목록의 마지막 요소를 가져오는 우아한 방법은 없습니다(예: items[-1]
(Python) ★★★★★★★★★★★★★★★★★★★★★★★★.
쓰셔야 돼요.list.get(list.size()-1)
.
복잡한 메서드 호출에 의해 취득된 목록을 사용할 경우 회피책은 다음과 같은 임시 변수에 있습니다.
List<E> list = someObject.someMethod(someArgument, anotherObject.anotherMethod());
return list.get(list.size()-1);
이것은 보기 흉하고 비싼 버전이나 작동하지 않는 버전을 피하기 위한 유일한 옵션입니다.
return someObject.someMethod(someArgument, anotherObject.anotherMethod()).get(
someObject.someMethod(someArgument, anotherObject.anotherMethod()).size() - 1
);
Java API에 이 디자인 결함의 수정이 도입되었으면 좋겠습니다.
" " " 를 .ArrayList
잠 an an ArrayDeque
이 있어요.removeLast
.
하면 "LinkedList"만으로 첫 수 .getFirst()
★★★★★★★★★★★★★★★★★」getLast()
( 및 (size() -1 get(0)보다
실행
Linked List 선언
LinkedList<Object> mLinkedList = new LinkedList<>();
원하는 것을 얻기 위해 사용할 수 있는 방법은 다음과 같습니다.이 경우 목록의 FIRST 및 LAST 요소에 대해 설명합니다.
/**
* Returns the first element in this list.
*
* @return the first element in this list
* @throws NoSuchElementException if this list is empty
*/
public E getFirst() {
final Node<E> f = first;
if (f == null)
throw new NoSuchElementException();
return f.item;
}
/**
* Returns the last element in this list.
*
* @return the last element in this list
* @throws NoSuchElementException if this list is empty
*/
public E getLast() {
final Node<E> l = last;
if (l == null)
throw new NoSuchElementException();
return l.item;
}
/**
* Removes and returns the first element from this list.
*
* @return the first element from this list
* @throws NoSuchElementException if this list is empty
*/
public E removeFirst() {
final Node<E> f = first;
if (f == null)
throw new NoSuchElementException();
return unlinkFirst(f);
}
/**
* Removes and returns the last element from this list.
*
* @return the last element from this list
* @throws NoSuchElementException if this list is empty
*/
public E removeLast() {
final Node<E> l = last;
if (l == null)
throw new NoSuchElementException();
return unlinkLast(l);
}
/**
* Inserts the specified element at the beginning of this list.
*
* @param e the element to add
*/
public void addFirst(E e) {
linkFirst(e);
}
/**
* Appends the specified element to the end of this list.
*
* <p>This method is equivalent to {@link #add}.
*
* @param e the element to add
*/
public void addLast(E e) {
linkLast(e);
}
그럼, 을 사용할 수 있습니다.
mLinkedList.getLast();
목록의 마지막 요소를 가져옵니다.
와 같이, 「」의 는,List
, 비어있다, 비어있다.IndexOutOfBoundsException
. 보다 좋은 방법은 ' 낫다'를 사용하는 입니다.Optional
삭제:
public class ListUtils {
public static <T> Optional<T> last(List<T> list) {
return list.isEmpty() ? Optional.empty() : Optional.of(list.get(list.size() - 1));
}
}
의 마지막 상 of of음음음음 as of음 。Optional
:
var list = List.of(10, 20, 30);
assert ListUtils.last(list).orElse(-1) == 30;
또, 빈 리스트에도 적절히 대응합니다.
var emptyList = List.<Integer>of();
assert ListUtils.last(emptyList).orElse(-1) == -1;
빈 목록을 고려하는 라이너는 다음과 같습니다.
T lastItem = list.size() == 0 ? null : list.get(list.size() - 1);
또는 null 값이 마음에 들지 않는 경우(퍼포먼스는 문제가 되지 않습니다)
Optional<T> lastItem = list.stream().reduce((first, second) -> second);
Spring 프로젝트가 있는 경우,CollectionUtils.lastElement
봄(javadoc)부터이므로 Google Guava와 같은 추가 종속성을 추가할 필요가 없습니다.
이것은 null-safe이므로 null을 통과하면 null이 반환됩니다.단, 대응을 취급할 때는 주의해 주십시오.
이를 입증하기 위한 장치 테스트는 다음과 같습니다.
@Test
void lastElementOfList() {
var names = List.of("John", "Jane");
var lastName = CollectionUtils.lastElement(names);
then(lastName)
.as("Expected Jane to be the last name in the list")
.isEqualTo("Jane");
}
@Test
void lastElementOfSet() {
var names = new TreeSet<>(Set.of("Jane", "John", "James"));
var lastName = CollectionUtils.lastElement(names);
then(lastName)
.as("Expected John to be the last name in the list")
.isEqualTo("John");
}
주의:org.assertj.core.api.BDDAssertions#then(java.lang.String)
는 어설션에 사용됩니다.
ArrayList의 인덱스는 0에서 시작하여 실제 크기보다 한 자리 먼저 끝나므로 마지막 배열 목록 요소를 반환하는 올바른 문장은 다음과 같습니다.
int last = mylist.get(mylist.size()-1);
예를 들어 다음과 같습니다.
배열 목록의 크기가 5인 경우 size-1 = 4이면 마지막 배열 요소가 반환됩니다.
guava는 마지막 요소를 얻는 다른 방법을 제공한다.List
:
last = Lists.reverse(list).get(0)
제공된 리스트가 비어 있는 경우 이 리스트는IndexOutOfBoundsException
이건 나한테 효과가 있었어.
private ArrayList<String> meals;
public String take(){
return meals.remove(meals.size()-1);
}
목록의 마지막 항목은list.size() - 1
수집은 어레이에 의해 백업되며 어레이는 인덱스0부터 시작합니다.
따라서 목록 요소 1은 배열의 인덱스 0에 있습니다.
목록의 요소 2는 배열의 인덱스 1에 있습니다.
목록의 요소 3은 배열의 인덱스 2에 있습니다.
기타 등등..
이건 어때..너희 반 어디선가...
List<E> list = new ArrayList<E>();
private int i = -1;
public void addObjToList(E elt){
i++;
list.add(elt);
}
public E getObjFromList(){
if(i == -1){
//If list is empty handle the way you would like to... I am returning a null object
return null; // or throw an exception
}
E object = list.get(i);
list.remove(i); //Optional - makes list work like a stack
i--; //Optional - makes list work like a stack
return object;
}
목록을 수정하는 경우 마지막 인덱스를 사용하여 반복하십시오(즉,size()-1
를 참조해 주세요).다시 실패하면 목록 구조를 확인하십시오.
size()를 사용하여 Arraylist의 마지막 값을 가져오기만 하면 됩니다.예를 들어, 정수의 ArrayList를 사용하는 경우 마지막 값을 얻으려면
int lastValue = arrList.get(arrList.size()-1);
배열 목록의 요소는 인덱스 값을 사용하여 액세스할 수 있습니다.따라서 ArrayLists는 일반적으로 항목 검색에 사용됩니다.
배열은 '길이'라는 로컬 변수에 크기를 저장합니다."a"라는 이름의 배열에서는 인덱스 값을 몰라도 다음을 사용하여 마지막 인덱스를 참조할 수 있습니다.
a[a.length-1]
사용할 마지막 인덱스에 값 5를 할당하려면:
a[a.length-1]=5;
JavaScript에서 배열 목록의 마지막 값을 가져오려면:
var yourlist = ["1","2","3"];
var lastvalue = yourlist[yourlist.length -1];
출력은 3 입니다.
Stream API를 사용할 수도 있습니다.
list.stream().reduce((first, second) -> second)
마지막 요소의 Optional이 됩니다.
이런 을 사용할 수 있습니다.last
val lastItem = list.last()
언급URL : https://stackoverflow.com/questions/687833/how-to-get-the-last-value-of-an-arraylist
'programing' 카테고리의 다른 글
새 파일에 쓸 때 전체 경로 자동 생성 (0) | 2022.08.30 |
---|---|
Vuex 저장소 상태가 변경될 때 Vue 구성 요소 속성을 업데이트하는 방법을 선택하십시오. (0) | 2022.08.30 |
Vue 리소스 - http 메서드를 동적으로 결정합니다. (0) | 2022.08.30 |
CXF 또는 JAX-WS에서 생성된 웹 서비스 클라이언트에서 WSDL 위치를 지정할 필요가 없도록 하려면 어떻게 해야 합니까? (0) | 2022.08.30 |
Java의 정적 메서드에서 클래스 이름 가져오기 (0) | 2022.08.30 |