Java 8中Arrays.stream过滤空串转Long数组报错问题排查
问题分析与修复:ArrayStoreException 异常原因解析
你遇到的ArrayStoreException其实是个典型的类型不匹配问题,咱们一步步拆解:
核心问题
你的代码里,Arrays.stream(productIdParams)生成的是**Stream<String>**(因为productIdParams是String[]数组),但你直接调用toArray(Long[]::new)试图把这些字符串塞进Long类型的数组里——Java的数组是严格类型安全的,String和Long没有继承关系,自然会抛出数组存储异常。
而且你加的filter(productId -> !productId.isEmpty())完全是多余的:Guava的Splitter.on(",").omitEmptyStrings()已经帮你过滤掉了空字符串,这一步属于重复操作。
修复后的代码
只需要在Stream流里加一步字符串转Long的映射操作,就能解决问题:
String test = "1,"; String[] productIdParams = Iterables.toArray( com.google.common.base.Splitter.on(",").omitEmptyStrings().split(test), String.class ); try { Long[] productIds = Arrays.stream(productIdParams) // 关键步骤:把String转换为Long类型 .map(Long::valueOf) .toArray(Long[]::new); System.out.println(productIds[0]); } catch (Exception e) { e.printStackTrace(); }
额外优化:处理非法数字场景
如果你的输入字符串可能包含非数字内容(比如"1,abc,"),可以在映射时添加异常处理,避免NumberFormatException:
Long[] productIds = Arrays.stream(productIdParams) .map(s -> { try { return Long.valueOf(s); } catch (NumberFormatException e) { // 根据业务需求处理:比如返回null后过滤,或者抛出自定义异常 System.err.println("无效的数字格式:" + s); return null; } }) // 过滤掉转换失败的null值 .filter(Objects::nonNull) .toArray(Long[]::new);
内容的提问来源于stack exchange,提问作者user826323
相关产品推荐
相关产品推荐

