有两个现有的方法名为getDetails(...)。一个要求至少有一个强制参数,另一个需要集合(不验证集合的内容/大小)。
问题是,集合有时作为空传递,根据我的业务案例,我总是期望传递一个最小值。因此,我需要使方法private,它接受集合。
// There are two params, to make sure that at-least one is passed by the caller
public static CustomerContext getDetails(int id, int... ids) {
Collection<Integer> idCollection = Instream.of(ids).boxed().collect(Collectors.toSet());
if(!idCollection.contains(id)){
idCollection.add(id);
}
return getDetails(idCollection);
}我计划将下面的方法作用域设置为private,这样调用者就不会使用Zero属性调用该方法。
public static CustomerContext getDetails(Collection<Integer> idCollection) {
return getDetails(idCollection,false);
}调用方之一是将Collection对象传递给getDetails,如下所示,
CustomerContext.getDetails(id.getDetails().values());id.getDetails()如下所示,
public Map<Id,Integer> getDetails(){
return Collections.unmodifiableMap(details);
}我正在寻找一种将集合id.getDetails().values()转换为int[]以传递到getDetails(int id,int... ids)而不是调用getDetails(Collection<Integer> idCollection)的方法。
我可以按下面的方式将集合转换为Integer[],
(Integer[])id.getDetails().values().toArray()我没有找到一种将集合转换到int[]的方法。
任何建议都会有很大帮助。
我已提及一些现有的问题,但未能解决我的问题:
发布于 2022-06-13 16:09:33
集合到Integer[]
当您需要获得Integer[]类型的结果时,您必须在调用toArray()时提供一个参数作为参数,不需要应用强制转换(如果没有传递参数toArray(),则返回数组Object[])。
Integer[] arr = id.getDetails().values().toArray(Integer[]::new);集合到int[]
无法将Integer类型的集合或数组Integer[]直接转换为数组int[]。这是不可能从另一个简单地做铸造,这些类型是不兼容的。
您必须遍历源并填充新创建的int[]数组。可以使用循环“手动”完成,或者以更方便的方式处理流,总体方法不会改变。
这就是如何使用Stream来完成的:
int[] arr = id.getDetails().values().stream() // Stream<Integer> - stream of objects
.mapToInt(Integer::intValue) // IntStream - stream of primitives
.toArray();发布于 2022-06-13 16:23:31
不能将Collection<Integer>转换为int[],但可以创建数组:
int[] values = id.getDetails().values().stream()
.mapToInt(n -> n)
.toArray();一边..。此代码:
if (!idCollection.contains(id)) {
idCollection.add(id);
}可改为:
idCollection.add(id);因为idCollection是一个Set,这就是sets的工作方式。它被声明为Collection并不重要;它是一个Set。
https://stackoverflow.com/questions/72605684
复制相似问题