使用Java中的Integers填充任意集合

时间:2016-11-24 15:37:53

标签: java collections java-8 java-stream

第一个问题,请理解格式错误。

在java中,使用流,可以使用Intstream

填充整数集合。
IntStream.range(from,to).boxed().collect(Collectors.toCollection(HashSet::new));

如果您使用例如HashSetArrayList替换LinkedList,那么您只需返回指定的集合。

使用此方法,您如何设置一个方法,您可以指定要填充的所需集合界面?我正在寻找的是这样的:

public returnType fillWithInt(Class<?> t, int from, int to){
   return IntStream.range(from,to)
       .boxed() 
       .collect(Collectors.toCollection(t::new));
}

尝试这个我收到警告:

  

类(java.lang.ClassLoader中)&#39;在java.lang.Class。

中拥有私人访问权限

我一整天都在这上面,无法弄清楚该怎么做。

我不妨说作为免责声明,我在编程方面非常新,所以我可能会完全错误地解决这个问题。如果是这样的话,我希望能够在正确的方向上轻推!

1 个答案:

答案 0 :(得分:2)

在您尝试实现时,无法使用类的实例定义method reference,因此您需要实现目标Supplier的{​​{1}}。

您可以使用反射作为下一个:

Collection

示例:

public <C extends Collection<Integer>> C fillWithInt(Class<C> t, int from, int to) {
    return IntStream.range(from,to)
        .boxed()
        .collect(
            Collectors.toCollection(
                () -> {
                    try {
                        return t.newInstance();
                    } catch (InstantiationException | IllegalAccessException e) {
                        throw new IllegalArgumentException(e);
                    }
                }
            )
        );
}

或者只是提供Set<Integer> set = fillWithInt(HashSet.class, 1, 10); 作为您方法的参数,如下所示:

Supplier

示例:

public <C extends Collection<Integer>> C fillWithInt(Supplier<C> supplier, 
    int from, int to){
    return IntStream.range(from,to)
        .boxed()
        .collect(Collectors.toCollection(supplier));
}