有没有一种简洁的方法来迭代流,同时有权访问流中的索引?
String[] names = {"Sam","Pamela", "Dave", "Pascal", "Erik"};
List<String> nameList;
Stream<Integer> indices = intRange(1, names.length).boxed();
nameList = zip(indices, stream(names), SimpleEntry::new)
.filter(e -> e.getValue().length() <= e.getKey())
.map(Entry::getValue)
.collect(toList());
Run Code Online (Sandbox Code Playgroud)
与那里给出的LINQ示例相比,这似乎相当令人失望
string[] names = { "Sam", "Pamela", "Dave", "Pascal", "Erik" };
var nameList = names.Where((c, index) => c.Length <= index + 1).ToList();
Run Code Online (Sandbox Code Playgroud)
有更简洁的方法吗?
此外,看起来拉链已移动或被移除......
使用Java流,很容易找到与给定属性匹配的元素.
如:
String b = Stream.of("a1","b2","c3")
.filter(s -> s.matches("b.*"))
.findFirst().get();
System.out.println("b = " + b);
Run Code Online (Sandbox Code Playgroud)
产生:
b = b2
然而,通常人们在匹配后想要一个或多个值,而不是匹配本身.我只知道如何用旧时尚循环来做到这一点.
String args[] = {"-a","1","-b","2","-c","3"};
String result = "";
for (int i = 0; i < args.length-1; i++) {
String arg = args[i];
if(arg.matches("-b.*")) {
result= args[i+1];
break;
}
}
System.out.println("result = " + result);
Run Code Online (Sandbox Code Playgroud)
哪个会产生:
结果= 2
使用Java 8 Streams有一种干净的方法吗?例如,给定上面的数组和谓词,将结果设置为"2" s -> s.matches("-b.*").
如果你可以获得下一个值,那么也可以获得下一个N值或所有值的列表/数组,直到另一个谓词匹配为止s -> s.matches("-c.*").
我刚刚遇到的情况是我需要知道列表中元素的索引(位置),但只有一个谓词表达式来标识元素.我看过像Stream这样的Stream函数
int index = list.stream().indexOf(e -> "TESTNAME".equals(e.getName()));
Run Code Online (Sandbox Code Playgroud)
但无济于事.当然,我可以像这样写:
int index = list.indexOf(list.stream().filter(e -> "TESTNAME".equals(e.getName()))
.findFirst().get());
Run Code Online (Sandbox Code Playgroud)
但这会a)迭代列表两次(在最坏的情况下元素将是最后一个)和b)如果没有元素匹配谓词(我更喜欢-1索引)将失败.
我为此功能编写了一个实用工具方法:
public static <T> int indexOf(List<T> list, Predicate<? super T> predicate) {
int idx = 0;
for (Iterator<T> iter = list.iterator(); iter.hasNext(); idx++) {
if (predicate.test(iter.next())) {
return idx;
}
}
return -1;
}
Run Code Online (Sandbox Code Playgroud)
但是,由于这似乎是一个非常简单的算法,我原本期望它在Java 8 Stream API中的某个地方.我只是想念它,还是真的没有这样的功能?(额外的问题:如果没有这样的方法,是否有充分的理由?在函数式编程中使用索引可能是反模式吗?)