如何将整数拆分为多个除数及其余数的列表

How to split an integer to a list of many dividers and its remainder

我想创建集合(或立即 Stream),对于给定的整数创建包含其 n 个除数和余数的集合。下面是创建它的简单代码:

int initValue = 151;
int chanckValue = 50;

List<Integer> ints = new ArrayList<>();
int value = initValue;
while (value > chanckValue) {
    ints.add(chanckValue);
    value = value - chanckValue;
}
ints.add(value);

System.out.println(ints);

输出为:

[50, 50, 50, 1]

如何用Stream做到完美?最好是紧凑的方式。

更新

这只是用法示例。第二张图中的乘法可以用任何操作代替:

Stream.of(3, 54, 150, 151, 230)
.map(value -> {
    List<Integer> ints = new ArrayList<>();
    while (value > chanckValue) {
        ints.add(chanckValue);
        value = value - chanckValue;
    }
    ints.add(value);
    return ints;
})
.map(l -> l.stream()
        .map(v -> v * v)
        .collect(Collectors.toList())
)
.forEach(System.out::println);

您可以使用 Stream.flatMapStream.concat

对流使用递归
public static Stream<Integer> chunkval(int val, int chanckValue) {
        if (val > chanckValue)
            return Stream.concat(Stream.of(chanckValue), chunkval(val - chanckValue, chanckValue));
        return Stream.of(val);
    }

然后像这样调用上面的方法

Stream.of(3, 54, 150, 151, 230).flatMap(v -> chunkval(v,chanckValue)).collect(Collectors.toList()).forEach(System.out::println);

从评论中总结信息。作为 pointed out: 151 / 50 = 3 and 151 % 50 = 1 and 提供一个实现的例子:

int q = value/chanckValue, r = value%chanckValue;
IntStream is = IntStream.range(0, q).map(x -> chanckValue);
if(r != 0) is = IntStream.concat(is, IntStream.of(r));

List

的其他方法
List<Integer> ints = new ArrayList<>(Collections.nCopies(value / chanckValue, chanckValue));
if (value % chanckValue != 0) ints.add(value % chanckValue);

如果需要添加余数,则推迟ArrayList创建。

List<Integer> ints = Collections.nCopies(value / chanckValue, chanckValue);
if(value % chanckValue != 0) { 
  ints = new ArrayList<>(ints); 
  ints.add(value % chanckValue); 
}