3

I am doing some hands on exercise on java 8 stream features so thought of applying the knowledge with the problem Converting String of digits to List of integer

a typical test would look like

 @Test
    public void testGetListofIntegersFromString(){
        List<Integer> result = getIntegers("123456780");
        assertEquals(Arrays.asList(1,2,3,4,5,6,7,8,0),result);
    }

I have written below method

List<Integer> getIntegers(String value) {
       return IntStream.rangeClosed(0, value.length() - 1).map(i -> Integer.valueOf(value.substring(i,i+1))).collect(?????);
    }

I am stuck about which function to use to get The List Of Integers I tried collect(Collectors.toList()) Its giving compilation error.

Please suggest if we can follow different to solve this .

Tagir Valeev
  • 97,161
  • 19
  • 222
  • 334
Shirishkumar Bari
  • 2,692
  • 1
  • 28
  • 36
  • What's the compilation error? – FThompson Jul 16 '15 at 04:36
  • I am getting an like Error:(61, 109) java: method collect in interface java.util.stream.IntStream cannot be applied to given types; required: `java.util.function.Supplier,java.util.function.ObjIntConsumer,java.util.function.BiConsumer` found: `java.util.stream.Collector>` reason: cannot infer type-variable(s) R (actual and formal argument lists differ in length) – Shirishkumar Bari Jul 16 '15 at 04:40
  • Have you tried using [`mapToInt`](http://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#mapToInt-java.util.function.ToIntFunction-) instead of `map`? – FThompson Jul 16 '15 at 04:43
  • `mapToInt` method is not available in `IntStream` , Should I use the class `Stream` ? – Shirishkumar Bari Jul 16 '15 at 04:46
  • 1
    My mistake, I see the issue now; your stream is of `int` which cannot be used as a type parameter for list (you need `Integer`). This question thus boils down to the question asked [here](http://stackoverflow.com/q/23674624/1247781). Using `boxed().collect(Collectors.toList())` should work. – FThompson Jul 16 '15 at 04:52
  • yes it solved the issue. Thanks a lot – Shirishkumar Bari Jul 16 '15 at 04:59

1 Answers1

6

Use String.chars():

"123456780".chars().map(c -> c-'0').boxed().collect(Collectors.toList());
Tagir Valeev
  • 97,161
  • 19
  • 222
  • 334
  • why do not use this: c -> c - 48. – Kachna Jul 16 '15 at 05:45
  • 3
    @Win.ubuntu, because `'0'` is less obscure to the reader. I personally know many ASCII codes in both decimal and hexadecimal, but I guess no more than 10% of programmers can readily answer "what symbol corresponds to ASCII code 48". – Tagir Valeev Jul 16 '15 at 05:50
  • 3
    @Tagir Valeev: Right, even if we know the codepoints, `48` offers no advantage over `'0'`. And *if* we really have to show off in the code, we use `c -> c&017` anyway… – Holger Jul 16 '15 at 10:11
  • 3
    You may also consider `"123456780".chars().mapToObj(Character::getNumericValue).collect(Collectors.toList());` – Alexis C. Jul 16 '15 at 18:54