我正在进行一些有关Java 8流特性的实践练习,因此想将所学知识应用于问题“将数字字符串转换为整数列表”。
典型的测试看起来像这样:
我已经编写了下面的方法。
我卡在了使用哪个函数来获取整数列表上。我尝试过使用
典型的测试看起来像这样:
@Test
public void testGetListofIntegersFromString(){
List<Integer> result = getIntegers("123456780");
assertEquals(Arrays.asList(1,2,3,4,5,6,7,8,0),result);
}
我已经编写了下面的方法。
List<Integer> getIntegers(String value) {
return IntStream.rangeClosed(0, value.length() - 1).map(i -> Integer.valueOf(value.substring(i,i+1))).collect(?????);
}
我卡在了使用哪个函数来获取整数列表上。我尝试过使用
collect(Collectors.toList())
,但出现了编译错误。请建议是否有其他解决方案。
java.util.function.Supplier<R>,java.util.function.ObjIntConsumer<R>,java.util.function.BiConsumer<R,R>
found:java.util.stream.Collector<java.lang.Object,capture#1 of ?,java.util.List<java.lang.Object>>
reason: cannot infer type-variable(s) R (actual and formal argument lists differ in length)。 - Shirishkumar BarimapToInt
代替map
吗? - FThompsonmapToInt
方法在IntStream
中不可用,我应该使用Stream
类吗? - Shirishkumar Bariint
类型,不能用作列表的类型参数(需要Integer
)。因此这个问题归结为这里所问的问题。使用boxed().collect(Collectors.toList())
应该可以解决。 - FThompson