What is the best/efficient way to convert HashSet of type <String>
to HashSet of type <Long>
?
Asked
Active
Viewed 85 times
0

Manos Nikolaidis
- 21,608
- 12
- 74
- 82

Prasad Revanaki
- 783
- 4
- 10
- 23
-
may be by trying out some actual code? try lambda expressions from java 8. would give you the solution in single line – sidgate Oct 30 '15 at 09:35
2 Answers
3
Set<Long> longSet = stringSet.stream().map(s-> Long.parseLong(s))
.collect(Collectors.toSet());
I haven't tried it out but should work

sidgate
- 14,650
- 11
- 68
- 119
-
3`s-> Long.parseLong(s)` could be a method reference: `Long::parseLong`. – Christoffer Hammarström Oct 30 '15 at 10:39
0
An improvement to sidgate's answer [when working with really large sets]: you can use parallelStream() it should be more efficient on large set, and replace Long.parseLong(s) with method reference.
Set<Long> longSet = stringSet.parallelStream()
.map(Long::parseLong)
.collect(Collectors.toSet());
[Edit] As noted in the comments, use parallelStream() only when working with really large sets, as it adds considerable amount of overhead.

Community
- 1
- 1

ttarczynski
- 949
- 1
- 10
- 19
-
`parallelStream` though useful, shouldn't be used for such simpler use case. http://zeroturnaround.com/rebellabs/java-parallel-streams-are-bad-for-your-health/ – sidgate Oct 30 '15 at 10:26
-
No, don't use `parallelStream` unless you have more than 10,000-100,000 elements and have measured that using `parallelStream` will be an improvement. – Christoffer Hammarström Oct 30 '15 at 10:39
-