如果您不介意使用第三方库,
Eclipse Collections提供了
zipWithIndex
和
forEachWithIndex
可用于许多类型。以下是使用
zipWithIndex
解决此挑战的JDK类型和Eclipse Collections类型的一组解决方案。
String[] names = { "Sam", "Pamela", "Dave", "Pascal", "Erik" };
ImmutableList<String> expected = Lists.immutable.with("Erik");
Predicate<Pair<String, Integer>> predicate =
pair -> pair.getOne().length() <= pair.getTwo() + 1;
List<String> strings1 = ArrayIterate.zipWithIndex(names)
.collectIf(predicate, Pair::getOne);
Assert.assertEquals(expected, strings1);
List<String> list = Arrays.asList(names);
List<String> strings2 = ListAdapter.adapt(list)
.zipWithIndex()
.collectIf(predicate, Pair::getOne);
Assert.assertEquals(expected, strings2);
MutableList<String> mutableNames = Lists.mutable.with(names);
MutableList<String> strings3 = mutableNames.zipWithIndex()
.collectIf(predicate, Pair::getOne);
Assert.assertEquals(expected, strings3);
ImmutableList<String> immutableNames = Lists.immutable.with(names);
ImmutableList<String> strings4 = immutableNames.zipWithIndex()
.collectIf(predicate, Pair::getOne);
Assert.assertEquals(expected, strings4);
MutableList<String> strings5 = mutableNames.asLazy()
.zipWithIndex()
.collectIf(predicate, Pair::getOne, Lists.mutable.empty());
Assert.assertEquals(expected, strings5);
这里有一个使用
forEachWithIndex
的解决方案。
MutableList<String> mutableNames =
Lists.mutable.with("Sam", "Pamela", "Dave", "Pascal", "Erik");
ImmutableList<String> expected = Lists.immutable.with("Erik");
List<String> actual = Lists.mutable.empty();
mutableNames.forEachWithIndex((name, index) -> {
if (name.length() <= index + 1)
actual.add(name);
});
Assert.assertEquals(expected, actual);
如果您将上述代码中的lambda更改为匿名内部类,则所有这些代码示例都可以在Java 5-7中正常工作。
注意:我是Eclipse Collections的提交者。
intRange()
是什么?我在 Java 8 中还没有遇到过这个方法。 (翻译者注:原文中的 "accross" 应为 "across",已进行修正。) - Rohit JainIntStream.rangeClosed(x, y)
。 - assyliasList<String> allCities = map.values().stream().flatMap(list -> list.stream()).collect(Collectors.toList());
更好地完成挑战4。 - assyliaszip
已经被移除了,还有实验性质的双值流,也称为BiStream
或MapStream
。主要问题在于,为了有效地执行此操作,Java 确实需要一个结构类型的二元组(或元组)类型。由于缺乏这样一个类型,很容易创建一个通用的 Pair 或 Tuple 类 - 这已经做过很多次了 - 但它们都会被擦除到相同的类型。 - Stuart Marks