Java 8: how to convert a list to a list using lambda
•
Java
I'm trying to split the list into lists, where the maximum size of each list is 4
I want to know how to do this with Lambdas
At present, I am doing this in the following ways:
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; }
UPDATE
There seems to be no easy way to split a list using Lambdas Although all the answers are very popular, they are also a good example of Lambdas not simplifying things
Solution
Try this method:
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 can be optimized instead of:
new ArrayList<>(Collections.singletonList(item))
Use this one:
List<List<T>> newList = new ArrayList<>(size); newList.add(item); return newList;
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码