使用Java8流对列表的第一个元素执行特定操作 [英] Performing specific operation on first element of list using Java8 streaming
问题描述
我想对列表的第一个元素执行某些操作,并对所有剩余元素执行不同的操作。
I want to perform certain operation on first element of my list and different operation for all remaining elements.
这是我的代码片段:
List<String> tokens = getDummyList();
if (!tokens.isEmpty()) {
System.out.println("this is first token:" + tokens.get(0));
}
tokens.stream().skip(1).forEach(token -> {
System.out.println(token);
});
有没有更简洁的方法来实现这一点,最好是使用java 8流API。
Is there any more cleaner way to achieve this preferably using java 8 streaming API.
推荐答案
表达意图的一种方式是
Spliterator<String> sp = getDummyList().spliterator();
if(sp.tryAdvance(token -> System.out.println("this is first token: "+token))) {
StreamSupport.stream(sp, false).forEach(System.out::println);
}
适用于任意 Collection
s,不仅列表
s,当更高级<$ c $时,可能比跳过
的解决方案更有效率c> Stream 操作被链接。此模式也适用于 Stream
源,即无法进行多次遍历或可能产生两种不同的结果。
which works with arbitrary Collection
s, not only List
s and is potentially more efficient than skip
based solutions when more advanced Stream
operations are chained. This pattern is also applicable to a Stream
source, i.e. when multiple traversal is not possible or could yield two different results.
Spliterator<String> sp=getDummyList().stream().filter(s -> !s.isEmpty()).spliterator();
if(sp.tryAdvance(token -> System.out.println("this is first non-empty token: "+token))) {
StreamSupport.stream(sp, false).map(String::toUpperCase).forEach(System.out::println);
}
但是,第一个元素的特殊处理可能仍会导致性能下降,与平均处理所有流元素相比。
However, the special treatment of the first element might still cause a performance loss, compared to processing all stream elements equally.
如果您只想应用 forEach
之类的操作,那么也可以使用 Iterator
:
If all you want to do is applying an action like forEach
, you can also use an Iterator
:
Iterator<String> tokens = getDummyList().iterator();
if(tokens.hasNext())
System.out.println("this is first token:" + tokens.next());
tokens.forEachRemaining(System.out::println);
这篇关于使用Java8流对列表的第一个元素执行特定操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!