0

What is the best/efficient way to convert HashSet of type <String> to HashSet of type <Long> ?

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 Answers2

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
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.

More on the topic

Community
  • 1
  • 1
ttarczynski
  • 949
  • 1
  • 10
  • 19