Java: split a List into two sub-Lists?

后端 未结 14 1517
执笔经年
执笔经年 2020-12-08 02:29

What\'s the simplest, most standard, and/or most efficient way to split a List into two sub-Lists in Java? It\'s OK to mutate the original List, so no copying should be nece

相关标签:
14条回答
  • 2020-12-08 03:13

    Likewise cribbing off of Marc's list, we'll use List.removeAll() to remove the duplicate entries from the second list. Note that, strictly speaking, this only follows the specs if the original list contained no duplicate items: otherwise, the original list may be missing items.

    <T> List<T> split(List<T> list, int i) {
            List<T> x = new ArrayList<T>(list.subList(i, list.size()));
            // Remove items from end of original list
            list.removeAll(x);
            return x;
    }
    
    0 讨论(0)
  • 2020-12-08 03:14

    A generic function to split a list to a list of list of specific size. I was missing this for long in java collections.

    private List<List<T>> splitList(List<T> list, int maxListSize) {
            List<List<T>> splittedList = new ArrayList<List<T>>();
            int itemsRemaining = list.size();
            int start = 0;
    
            while (itemsRemaining != 0) {
                int end = itemsRemaining >= maxListSize ? (start + maxListSize) : itemsRemaining;
    
                splittedList.add(list.subList(start, end));
    
                int sizeOfFinalList = end - start;
                itemsRemaining = itemsRemaining - sizeOfFinalList;
                start = start + sizeOfFinalList;
            }
    
            return splittedList;
        }
    
    0 讨论(0)
提交回复
热议问题