本文介绍了Java 8:如何使用lambda将列表转换为列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试将列表拆分为列表,其中每个列表的最大大小为4.
I'm trying to split a list into a list of list where each list has a maximum size of 4.
我想知道这是怎么回事使用lambdas。
I would like to know how this is possible to do using lambdas.
目前我正在做的方式如下:
Currently the way I'm doing it is as follow:
List<List<Object>> listOfList = new ArrayList<>();
final int MAX_ROW_LENGTH = 4;
int startIndex =0;
while(startIndex <= listToSplit.size() )
{
int endIndex = ( ( startIndex+MAX_ROW_LENGTH ) < listToSplit.size() ) ? startIndex+MAX_ROW_LENGTH : listToSplit.size();
listOfList.add(new ArrayList<>(listToSplit.subList(startIndex, endIndex)));
startIndex = startIndex+MAX_ROW_LENGTH;
}
更新
似乎没有一种简单的方法可以使用lambdas来拆分列表。虽然所有答案都非常受欢迎,但它们也是lambda不简化事物的一个很好的例子。
It seems that there isn't a simple way to use lambdas to split lists. While all of the answers are much appreciated, they're also a wonderful example of when lambdas do not simplify things.
推荐答案
尝试这种方法:
static <T> List<List<T>> listSplitter(List<T> incoming, int size) {
// add validation if needed
return incoming.stream()
.collect(Collector.of(
ArrayList::new,
(accumulator, item) -> {
if(accumulator.isEmpty()) {
accumulator.add(new ArrayList<>(singletonList(item)));
} else {
List<T> last = accumulator.get(accumulator.size() - 1);
if(last.size() == size) {
accumulator.add(new ArrayList<>(singletonList(item)));
} else {
last.add(item);
}
}
},
(li1, li2) -> {
li1.addAll(li2);
return li1;
}
));
}
System.out.println(
listSplitter(
Arrays.asList(0, 1, 2, 3, 4, 5, 6, 7, 8, 9),
4
)
);
另请注意,此代码可以进行优化,而不是:
Also note that this code could be optimized, instead of:
new ArrayList<>(Collections.singletonList(item))
使用这一个:
List<List<T>> newList = new ArrayList<>(size);
newList.add(item);
return newList;
这篇关于Java 8:如何使用lambda将列表转换为列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!