I need to implement a method int minValue(int[] values)
using the Stream API.
The method takes an array of ints from 0 to 9, takes unique values, and returns a minimum possible number combined of these unique digits. The array must not be converted to a string.
Example #1: input {1,2,3,3,2,3}, returned value - 123;
Example #2: input {9,8}, returned value – 89.
I don’t know how to implement the multiplication of every stream member to the sequence of values using Stream API: if my sorted stream has values (5, 3, 1) I need to perform 5 * 1 + 3 * 10 + 1 * 100. How can I do this using Stream API?
My solution with a simple for loop is below:
private static int minValue(int[] values) {
int result = 0;
int capacity = 1;
int[] ints = Arrays.stream(values)
.boxed()
.distinct()
.sorted(Collections.reverseOrder())
.mapToInt(Integer::intValue).toArray();
for (int i = 0; i < ints.length; i++) {
result = result + ints[i] * capacity;
capacity = capacity * 10;
}
return result;
}