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

2.1k views Asked by At

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

There are 2 answers

0
Eugene On BEST ANSWER
 setIds.stream()
       .map(Long::valueOf)
       .toArray(Long[]::new);
0
Manasi On

you can use mapToLong(..) function and collect using .toArray() as

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

However for printing you need to loop on array or use stream

Arrays.stream(longIds).forEach(System.out::println);