如何使用 Java8 Lambda 表达式将 Set<String> 转换为 Long[] 数组

How to convert Set<String> to Long[] array using Java8 Lambda expressions

谁能告诉我如何使用 Java.

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)

您可以使用 mapToLong(..) 函数并使用 .toArray() 收集

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

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

Arrays.stream(longIds).forEach(System.out::println);
 setIds.stream()
       .map(Long::valueOf)
       .toArray(Long[]::new);