将数字字符串转换为整数列表

3
我正在进行一些有关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()),但出现了编译错误。请建议是否有其他解决方案。

编译错误是什么? - FThompson
我遇到了一个错误,类似于Error:(61, 109) java: method collect in interface java.util.stream.IntStream cannot be applied to given types; required: 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 Bari
你尝试过使用mapToInt代替map吗? - FThompson
mapToInt 方法在 IntStream 中不可用,我应该使用 Stream 类吗? - Shirishkumar Bari
1
我的错误,我现在看到问题了; 你的流是int类型,不能用作列表的类型参数(需要 Integer)。因此这个问题归结为这里所问的问题。使用 boxed().collect(Collectors.toList()) 应该可以解决。 - FThompson
是的,它解决了问题。非常感谢。 - Shirishkumar Bari
1个回答

6
使用String.chars()方法:
"123456780".chars().map(c -> c-'0').boxed().collect(Collectors.toList());

为什么不使用这个:c -> c - 48。 - Kachna
3
@Win.ubuntu,因为对读者来说'0'更不费解。我个人了解许多ASCII码,包括十进制和十六进制,但我猜只有不到10%的程序员能够轻松回答“哪个符号对应ASCII码48”。 - Tagir Valeev
3
@Tagir Valeev:没错,即使我们知道代码点,48 也不比 '0' 更优。而且 如果 我们真的必须在代码中炫耀,我们也会使用 c -> c&017 - Holger
3
您可以考虑使用 "123456780".chars().mapToObj(Character::getNumericValue).collect(Collectors.toList()); 这段代码。 - Alexis C.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接