我想对列表的第一个元素执行某些操作,并对所有剩余元素执行不同的操作。
这是我的代码片段:
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。
最佳答案
表达意图的一种方式是
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
,而不仅仅是 List
,并且当更高级的 时,它可能比基于
操作是链式的。此模式也适用于 skip
的解决方案更有效StreamStream
源,即当无法进行多次遍历或可能产生两个不同结果时。
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);
}
但是,与平等处理所有流元素相比,对第一个元素的特殊处理可能仍然会导致性能损失。
如果您只想应用forEach
之类的操作,您还可以使用Iterator
:
Iterator<String> tokens = getDummyList().iterator();
if(tokens.hasNext())
System.out.println("this is first token:" + tokens.next());
tokens.forEachRemaining(System.out::println);
关于java - 使用 Java8 流对列表的第一个元素执行特定操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40625519/