如何在Java8中使用Lambda表达式将Set <string>转换为Long []

时间:2018-08-31 13:33:35

标签: lambda collections java-8 set arraystoreexception

任何人都可以告诉如何将Set of String values转换为Long Array values

String singleId = "8432";
String[] ids = new String[]{"4562", "8432"};
Set<String> setIds = new HashSet<String>();
if (setIds != null && ids.length > 0){
    for (String id : ids){
        setIds.add(id);
    }
    setIds.add(singleId);
} else {
    setIds.add(singleId);
}
Long[] longIds = setIds.stream().toArray(Long[]::new);
System.out.println(longIds);

遇到错误

Exception in thread "main" java.lang.ArrayStoreException: java.lang.String
at java.util.stream.Nodes$FixedNodeBuilder.accept(Nodes.java:1222)
at java.util.HashMap$KeySpliterator.forEachRemaining(HashMap.java:1540)
at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481)
at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471)
at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:545)
at java.util.stream.AbstractPipeline.evaluateToArrayNode(AbstractPipeline.java:260)
at java.util.stream.ReferencePipeline.toArray(ReferencePipeline.java:438)
at com.java.collections.set.FilterDuplicatesBySet.main(FilterDuplicatesBySet.java:40)

2 个答案:

答案 0 :(得分:5)

 setIds.stream()
       .map(Long::valueOf)
       .toArray(Long[]::new);

答案 1 :(得分:2)

您可以使用Format : JSON Protocol : HTTP Event : Job Started URL Source : Plain Text URL : http://localhost:8080/xxx/xxx Timeout : 30000 ms Retries : 2 Log : 50 函数并使用mapToLong(..)作为收集对象

.toArray()

但是对于打印,您需要在数组上循环或使用流

long[] longIds = setIds.stream().mapToLong(Long::parseLong).toArray();