Robert Li :
I have a List<Integer>
like { 1, 2, 3 ,4, 5 }
, I'd like to get the result like 12345
.
How to do this using Java8 streams or any smart way?
List
consists of single digit non-negative integers.
I could definitely do like 1*10000+ 2 * 1000 + 3*100 + 4*10 + 5
, but it is quite tedious.
Andy Turner :
Use IntStream.reduce
:
int n = IntStream.of(array).reduce(0, (a,b) -> 10*a + b)
This is effectively the same as:
int n = 0;
for (int b : array) {
n = 10 * n + b;
}
Personally, I would opt for the latter in the absence of other constraints, since it is much simpler code, doesn't involve the relatively heavyweight streams framework, easier to debug etc.