I'm trying to print a concat Stream that includes String and Integer elements. I've try a few ways, but none of them works. I can't find a proper way to do it on internet. It's just a testing code as you can see:
import java.util.stream.*;
class testconcat{
public static void main(String[] args){
Stream<String> part1=Stream.of("Testing the ");
Stream<String> part2=Stream.of("streams concat");
Stream<String> part3=Stream.of(" on Java, dividing ");
Stream<String> part4=Stream.of("this phrase in ");
IntStream part5=IntStream.of(6);
Stream<String> part6=Stream.of(" parts.");
String phrase=Stream.concat(Stream.concat(Stream.concat(Stream.concat(Stream.concat(part1, part2), part3), part4), part5), part6);
System.out.println(phrase);
}
}
I know part5 is an Integer so I can't concat it on a regular way, so I also tried:
IntStream part5=IntStream.of(6);
Stream<String> part6=Stream.of(" parts.");
String phrase=Stream.concat(IntStream.concat(Stream.concat(Stream.concat(Stream.concat(part1, part2), part3), part4), part5), part6);
System.out.println(phrase);
}
}
and also:
Integer part5=6;
String part6=(" parts.");
String phrase=Stream.concat(Stream.concat(Stream.concat(Stream.concat(Stream.concat(part1, part2), part3), part4);
System.out.println(phrase + Integer.toString(part5) + part6);
}
}
None of which works. Is there a way to do that? Thanks in advance.
Wrong, IntStream is a specific stream of primitive
intvalue(s), and it is not the same as Stream, and therefore,IntStream::boxedorIntStream::mapToObjmust be invoked to produceStream<?>which can be used inStream::concat:However, such verbose Stream concatenation is redundant, and the
Streams can be joined usingStream.of + Stream::flatMap. In the example below,IntStreammapped to String immediately, so no extraStream::mapis needed: