Welcome
Act, In the living present.

Java: Split a List into two Sublists

How to get a sublist of an exist list by index in Java ?

java.jpg

package org.4spaces;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class SplitList {

    /**
     * naive
     *
     * @param originList 
     * @param fromIndex  inclusive
     * @param toIndex    exclusive
     * @return sublist
     */
    public List naiveSplit(List originList, int fromIndex, int toIndex) {
        List subList = new ArrayList();
        if (fromIndex >= 0 && toIndex <= originList.size()) {
            for (int i = 0; i < originList.size(); i++) {
                if (i >= fromIndex && i < toIndex) {
                    subList.add(originList.get(i));
                }
            }
        }
        return subList;
    }

    /**
     * Java List.subList
     *
     * @param originList 
     * @param fromIndex  inclusive
     * @param toIndex    exclusive
     * @return sublist
     */
    public List subListSplit(List originList, int fromIndex, int toIndex) {
        return originList.subList(fromIndex, toIndex);
    }

    /**
     * Java 8 Collectors.partitioningBy
     *
     * @param originList 
     * @param fromIndex  inclusive
     * @param toIndex    exclusive
     * @return sublist
     */
    public List partitioningBySplit(List originList, int fromIndex, int toIndex) {
        Map<Boolean, List> subList = (Map<Boolean, List>) originList.stream().collect(Collectors.partitioningBy(s -> originList.indexOf(s) >= fromIndex && originList.indexOf(s) < toIndex));
        return subList.get(true);
    }

    /**
     * Java 8 Collectors.groupingBy
     *
     * @param originList 
     * @param fromIndex  inclusive
     * @param toIndex    exclusive
     * @return sublist
     */
    public List groupingBySplit(List originList, int fromIndex, int toIndex) {
        Map<Boolean, List> subList = (Map<Boolean, List>) originList.stream().collect(Collectors.groupingBy(s -> originList.indexOf(s) >= fromIndex && originList.indexOf(s) < toIndex));
        return subList.get(true);
    }
}

Reference:

  1. List.subList(int fromIndex,int toIndex)
  2. java.util.stream.Collectors
赞(0)
未经允许不得转载:Michael's Blog » Java: Split a List into two Sublists

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址