-2

Can the following code be converted to stream? I have tried this a lot of times but I kind of got stuck in someplace.

Scanner sc = new Scanner(System.in);

while(sc.hasNext()) {
    String line = sc.nextLine();
    line.chars().forEach(i -> System.out.println((char)i));
}

sc.close();

2 Answers2

1

Yes, you can create a Spliterator from Scanner which can then be passed to StreamSupport#stream to create an IntStream. Here is an example:

Scanner sc = new Scanner(System.in);

try ( IntStream is = StreamSupport.stream(
            Spliterators.spliterator(sc, Long.MAX_VALUE, Spliterator.ORDERED), false)
        .onClose(sc::close)
        .flatMapToInt(s -> s.chars()); ) {
    is.forEach(i -> System.out.println((char) i));
}
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
Aniket Sahrawat
  • 12,410
  • 3
  • 41
  • 67
-1
Scanner sc = new Scanner(System.in);

while(sc.hasNext()) {
    String line = sc.nextLine();
    Arrays.stream(line.split(""))
            .forEach(System.out::println);
}

sc.close()
Yudhishthir Singh
  • 2,941
  • 2
  • 23
  • 42