java.util.stream에서 목록 가져오기Java 8에서의 스트림
컬렉션을 쉽게 필터링하기 위해 Java 8 람다를 가지고 놀고 있었습니다.그러나 같은 문장에서 결과를 새 목록으로 검색할 수 있는 간결한 방법을 찾지 못했습니다.지금까지의 가장 간결한 어프로치는 다음과 같습니다.
List<Long> sourceLongList = Arrays.asList(1L, 10L, 50L, 80L, 100L, 120L, 133L, 333L);
List<Long> targetLongList = new ArrayList<>();
sourceLongList.stream().filter(l -> l > 100).forEach(targetLongList::add);
인터넷 상의 예시는 새로운 결과 목록을 생성하지 않고 중지되었기 때문에 내 질문에 답하지 못했습니다.좀좀 、 간법한방방방 。난 예상했었어, 내가 예상한 바로는Stream
.toList()
,toSet()
, …
이 른 른 른 른 른 른 른 른 른 른 that that that that that that that that that that targetLongList
세 번째 줄에 의해 직접 할당될 수 있습니까?
으로 유지되는 한될 수 않은 경우 스트림이 순차에.sequential()로 하겠습니다.forEach
에 대한 그대로code]: sequential()가 입니다.forEach(targetLongList::add)
)는 수 있습니다는 스트림이 병렬일 경우 레이시합니다. 해도,은 의도한 못할 이다.forEach
는 명시적으로 확정적이지 않습니다.시퀀셜 스트림에서도 요소 처리 순서가 보장되지 않습니다. 하다 보면 써야 될 것 같아요.forEachOrdered
올바른 순서를 확인합니다.스트림 API 설계자의 의도는 다음과 같이 수집기를 사용하는 것입니다.]
또 다른 방법은
targetLongList = sourceLongList.stream()
.filter(l -> l > 100)
.collect(Collectors.toList());
갱신일 :
하나의 은 '보다 낫다'입니다.Collectors.toList
:
targetLongList =
sourceLongList.stream().
filter(l -> l > 100).
collect(Collectors.toList());
이전 솔루션:
하나의 은 '보다 낫다'입니다.Collectors.toCollection
:
targetLongList =
sourceLongList.stream().
filter(l -> l > 100).
collect(Collectors.toCollection(ArrayList::new));
util 을 반환하는 .ArrayList
내가 원할 때 말이야
Collectors.toCollection(ArrayList::new)
그런 일반적인 작업에는 조금 시끄럽습니다.
예:
ArrayList<Long> result = sourceLongList.stream()
.filter(l -> l > 100)
.collect(toArrayList());
public static <T> Collector<T, ?, ArrayList<T>> toArrayList() {
return Collectors.toCollection(ArrayList::new);
}
또, 커스텀 콜렉터의 작성과 사용이 얼마나 간단한지도 설명하겠습니다.이것은 일반적으로 매우 편리합니다.
collect(Collectors.toList());
이것은 스트림을 목록으로 변환하기 위해 사용할 수 있는 콜입니다.
구체적으로는 다음과 같습니다.
List<String> myList = stream.collect(Collectors.toList());
송신원:
https://www.geeksforgeeks.org/collectors-tolist-method-in-java-with-examples/
기본 요소 배열이 있는 경우 Eclipse 컬렉션에서 사용할 수 있는 기본 컬렉션을 사용할 수 있습니다.
LongList sourceLongList = LongLists.mutable.of(1L, 10L, 50L, 80L, 100L, 120L, 133L, 333L);
LongList targetLongList = sourceLongList.select(l -> l > 100);
sourceLongList에서 수 List
:
List<Long> sourceLongList = Arrays.asList(1L, 10L, 50L, 80L, 100L, 120L, 133L, 333L);
List<Long> targetLongList =
ListAdapter.adapt(sourceLongList).select(l -> l > 100, new ArrayList<>());
「 」를 사용하고 LongStream
:
long[] sourceLongs = new long[]{1L, 10L, 50L, 80L, 100L, 120L, 133L, 333L};
LongList targetList =
LongStream.of(sourceLongs)
.filter(l -> l > 100)
.collect(LongArrayList::new, LongArrayList::add, LongArrayList::addAll);
주의: 저는 이클립스 컬렉션에 기고하고 있습니다.
좀 더 효율적인 방법(소스 목록 작성 및 필터에 의한 자동 언박스를 피함)
List<Long> targetLongList = LongStream.of(1L, 10L, 50L, 80L, 100L, 120L, 133L, 333L)
.filter(l -> l > 100)
.boxed()
.collect(Collectors.toList());
Java 16에는 새로운 메서드 Stream.toList()가 있습니다.
List<Long> targetLongList = sourceLongList
.stream()
.filter(l -> l > 100)
.toList();
서드파티 라이브러리를 사용해도 괜찮으시다면 AOL의 cyclops-react lib(Disclosure I am a contributor)에는 List를 포함한 모든 JDK Collection 유형에 대한 확장자가 있습니다.ListX 인터페이스는 java.util을 확장합니다.필터를 포함하여 유용한 연산자를 많이 나열하고 추가합니다.
간단하게 쓸 수 있습니다.
ListX<Long> sourceLongList = ListX.of(1L, 10L, 50L, 80L, 100L, 120L, 133L, 333L);
ListX<Long> targetLongList = sourceLongList.filter(l -> l > 100);
ListX는 기존 목록(ListX.fromItable 경유)에서 작성할 수도 있습니다.
LongStream 클래스에서 제공되는 수집 메서드의 다른 배리언트 및 IntStream 및 DoubleStream 클래스에서도 동일하게 제공됩니다.
<R> R collect(Supplier<R> supplier,
ObjLongConsumer<R> accumulator,
BiConsumer<R,R> combiner)
이 스트림의 요소에 대해 가변 축소 작업을 수행합니다.가변환원이란 축소된 값이 ArrayList와 같은 가변결과 컨테이너로, 결과를 대체하는 것이 아니라 결과 상태를 갱신함으로써 요소가 통합되는 것입니다.그 결과, 다음과 같은 결과가 됩니다.
R result = supplier.get();
for (long element : this stream)
accumulator.accept(result, element);
return result;
reduce(long, LongBinaryOperator)와 마찬가지로 추가 동기화 없이 수집 작업을 병렬화할 수 있습니다.이것은 터미널 조작입니다.
그리고 이 수집 방법에 대한 당신의 질문에 대한 답변은 다음과 같습니다.
LongStream.of(1L, 2L, 3L, 3L).filter(i -> i > 2)
.collect(ArrayList::new, (list, value) -> list.add(value)
, (list1, list2) -> list1.addAll(list2));
다음은 매우 스마트하지만 이해하기 어려운 메서드 참조 바리안트입니다.
LongStream.of(1L, 2L, 3L, 3L).filter(i -> i > 2)
.collect(ArrayList::new, List::add , List::addAll);
HashSet 배리언트는 다음과 같습니다.
LongStream.of(1L, 2L, 3L, 3).filter(i -> i > 2)
.collect(HashSet::new, HashSet::add, HashSet::addAll);
마찬가지로 LinkedList 배리언트는 다음과 같습니다.
LongStream.of(1L, 2L, 3L, 3L)
.filter(i -> i > 2)
.collect(LinkedList::new, LinkedList::add, LinkedList::addAll);
(나 같은) 누군가가 원시적인 타입이 아닌 오브젝트를 다루는 방법을 찾고 있는 경우
String ss = "An alternative way is to insert the following VM option before "
+ "the -vmargs option in the Eclipse shortcut properties(edit the "
+ "field Target inside the Shortcut tab):";
List<Character> ll = ss
.chars()
.mapToObj(c -> new Character((char) c))
.collect(Collectors.toList());
System.out.println("List type: " + ll.getClass());
System.out.println("Elem type: " + ll.get(0).getClass());
ll.stream().limit(50).forEach(System.out::print);
인쇄:
List type: class java.util.ArrayList
Elem type: class java.lang.Character
An alternative way is to insert the following VM o
String joined =
Stream.of(isRead?"read":"", isFlagged?"flagged":"", isActionRequired?"action":"", isHide?"hide":"")
.filter(s -> s != null && !s.isEmpty())
.collect(Collectors.joining(","));
여기 AbacusUtil의 코드가 있습니다.
LongStream.of(1, 10, 50, 80, 100, 120, 133, 333).filter(e -> e > 100).toList();
공개: 저는 Abacus Util의 개발자입니다.
코드는 다음과 같이 고쳐 쓸 수 있습니다.
List<Long> sourceLongList = Arrays.asList(1L, 10L, 50L, 80L, 100L, 120L, 133L, 333L);
List<Long> targetLongList = sourceLongList.stream().filter(l -> l > 100).collect(Collectors.toList());
가변 목록으로 수집하려면:
targetList = sourceList.stream()
.filter(i -> i > 100) //apply filter
.collect(Collectors.toList());
변경할 수 없는 목록에 수집하려면:
targetList = sourceList.stream()
.filter(i -> i > 100) //apply filter
.collect(Collectors.toUnmodifiableList());
설명collect
JavaDoc:
Collector를 사용하여 이 스트림의 요소에 대해 가변 축소 작업을 수행합니다.수집기는 수집 인수로 사용되는 함수(공급자, BiConsumer, BiConsumer)를 캡슐화하여 수집 전략을 재사용하고 다단계 그룹화 또는 분할과 같은 수집 작업을 구성할 수 있도록 합니다.스트림이 병렬이고 Collector가 동시이고 스트림이 비순서이거나 Collector가 비순서일 경우 동시 감소가 수행됩니다(동시 감소에 대한 자세한 내용은 Collector 참조).
이것은 터미널 조작입니다.
병렬로 실행되면 여러 중간 결과를 인스턴스화, 입력 및 병합하여 가변 데이터 구조의 분리를 유지할 수 있습니다.따라서 스레드 세이프 이외의 데이터 구조(ArrayList 등)와 병렬로 실행해도 병렬 감소를 위해 추가 동기화가 필요하지 않습니다.
★★★★★★★★★★★★★★★를 사용하지 않는 경우는parallel()
으로 동작합니다.
List<Long> sourceLongList = Arrays.asList(1L, 10L, 50L, 80L, 100L, 120L, 133L, 333L);
List<Long> targetLongList = new ArrayList<Long>();
sourceLongList.stream().peek(i->targetLongList.add(i)).collect(Collectors.toList());
언급URL : https://stackoverflow.com/questions/14830313/retrieving-a-list-from-a-java-util-stream-stream-in-java-8
'programing' 카테고리의 다른 글
Vue 라이프 사이클 리스너를 동적으로 추가하는 방법 (0) | 2022.06.12 |
---|---|
사용자 편집 가능한 Vue 템플릿 (0) | 2022.06.12 |
밀리초를 "hh:mm:ss" 형식으로 변환하는 방법 (0) | 2022.06.12 |
Vue.js - vue-axios 응답 데이터를 저장 및 표시하려고 할 때 공리가 정의되지 않음 (0) | 2022.06.12 |
변수 개수의 인수를 받아들이는 함수에 전달된 인수 수를 계산하는 방법은 무엇입니까? (0) | 2022.06.12 |