根据相似的索引收集列表的集合

时间:2019-02-12 13:01:16

标签: java loops collections java-8 iteration

我有一个类似的收藏: List<List<Object>> firstList

我想将相似的模式列表组合在一起: List<List<Object>> secondList 但按索引分组。

firstList [1]:
   0 = {Object A}"
   1 = {Object B}"
   2 = {Object C}"

firstList [2]:
   0 = {Object A}"
   1 = {Object B}"
   2 = {Object C}"

我想将此收藏归为

secondList [1]:
   0 = {Object A}"
   1 = {Object A}"

secondList [2]:
   0 = {Object B}"
   1 = {Object B}"

secondList [3]:
   0 = {Object C}"
   1 = {Object C}"

到目前为止我尝试过的是

for (int i = 0; i <firstList.size() ; i++) {
    List<Object> list = firstList.get(i);
    List<Object> rlPr = new ArrayList<>();

    for (int j = 0; j <list.size()-1; j++) {
        rlPr.add(list.get(i));
    }
    secondList.add(rlPr);
}

但是我没有得到预期的结果。 我正在使用Java 8。

编辑:所有列表大小均相同

4 个答案:

答案 0 :(得分:3)

您可以使用Map按索引对值进行分组:

Map<Integer, List<Object>> map = new TreeMap<>();
for (List<Object> objects : firstList) {
    for (int i = 0, l = objects.size(); i < l; i++) {
        map.computeIfAbsent(i, k -> new ArrayList<>()).add(objects.get(i));
    }
}

然后拿回List

List<List<Object>> secondList = new ArrayList<>(map.values());

答案 1 :(得分:2)

首先,获取子列表的最大长度。在您的情况下,两者均为3。遍历所有这些索引,从该索引处的每个子列表中获取值,然后将这些值收集到新的子列表中。

onLastWindowClosed()

即使子列表的长度不同,这也将起作用。

答案 2 :(得分:1)

假设主列表中的列表大小相同,则可以执行以下操作...

    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.Collections;
    import java.util.List;

    public class OhCrikey {

        public static void main(String[] args) {
            List<List<String>> lists = Arrays.asList(
                    Arrays.asList("1a", "2a", "3a"),
                    Arrays.asList("1b", "2b", "3b"),
                    Arrays.asList("1c", "2c", "3c")
            );

            List<List<String>> result = transform(lists);

            result.forEach(System.out::println);
        }

        private static <T> List<List<T>> transform(List<List<T>> lists) {
            if(lists == null || lists.isEmpty()) {
                return Collections.emptyList();
            }
            // Check each sub-list contains the same number of elements
            checkAllSameSize(lists);

            // Initialise the results list
            List<List<T>> result = new ArrayList<>();

            // Get the size of each sub-list
            int totalLists = lists.get(0).size();

            // Fill up the results list with 'totalLists' empty lists
            for(int k = 0; k < totalLists; k++) {
                result.add(new ArrayList<>());
            }

            // For each input list...
            lists.forEach(list -> {
                // Iterate over it and add the kth element to the kth result list.
                for(int k = 0; k < list.size(); k++) {
                    result.get(k).add(list.get(k));
                }
            });

            return result;
        }

        private static <T> void checkAllSameSize(List<List<T>> lists) {
            int size = lists.get(0).size();

            // Make sure each list has the same size as the first list
            lists.forEach(list -> {
                if(list.size() != size) {
                    throw new AssertionError("All child lists must have same number of elements.");
                }
            });
        }
    }

打印...

    [1a, 1b, 1c]
    [2a, 2b, 2c]
    [3a, 3b, 3c]

答案 3 :(得分:0)

将其作为一种流方法(将Object替换为CustomObject):

List<List<CustomObject>> secondList = new ArrayList<>( // Collection to ArrayList
       firstList.stream() // Stream<List<CustomObject>>
                .flatMap(Collection::stream) // Stream<CustomObject>
                .collect(Collectors.groupingBy(Function.identity())) // Map<CustomObject, List<CustomObject>>
                .values()); // Collection<List<CustomObject>>