javalambdacollectionsjava-8arraystoreexception

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


Can anybody tell, how to convert Set of String valuesinto Long Array values using Java.

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);

Getting below error

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)

Solution

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