Collectors.toList() showing error “Expected 3 argument but found 1”

你离开我真会死。 提交于 2020-12-29 08:12:16

问题


Why is my collect Collectors.toList() showing this error:

Expected 3 argument but found 1

package com.knoldus;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collector;
import java.util.stream.Collectors;
import java.util.stream.IntStream;


interface Cityeration<T> {
    public abstract List<T> Cityeration(List<T> first, List<T> Second);
}

public class ListMultiplication {
    public static void main(String s[]) {
        List firstList = Arrays.asList(1, 2, 3, 4, 5);
        List secondList = Arrays.asList(1, 2, 3, 4, 5);

        Cityeration c = (first, second) -> IntStream.range(0, first.size())
                        .map(i -> first.get(i) * second.get(i))
                        .collect(Collectors.toList());
    }
}

回答1:


import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

interface Cityeration<T> {
    public abstract List<T> cityeration(List<T> first, List<T> Second);
}

public class ListMultiplication {
    public static void main(String s[]) {
        List<Integer> firstList = Arrays.asList(1, 2, 3, 4, 5, 6);
        List<Integer> secondList = Arrays.asList(1, 2, 3, 4, 5);

        Cityeration<Integer> c = (first, second) -> IntStream
                .range(0, first.size() <= second.size() ? first.size() : second.size())
                .map(i -> first.get(i) * second.get(i)).boxed().collect(Collectors.toList());
        System.out.println(c.cityeration(firstList, secondList));
    }
}

Output:

[1, 4, 9, 16, 25]

Note: Make sure to

  1. use generic types instead of raw types.
  2. compare the sizes of the lists to avoid ArrayIndexOutOfBoundsException.


来源:https://stackoverflow.com/questions/60438117/collectors-tolist-showing-error-expected-3-argument-but-found-1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!