3

I would like to load each line in a file into HashSet collection. Is there a simple way to do this?

Omar Hrynkiewicz
  • 503
  • 1
  • 8
  • 21
MatBanik
  • 25,486
  • 39
  • 112
  • 177

4 Answers4

13

How about:

Sets.newHashSet(Files.readLines(file, charSet));

(using Guava).

References:

Simon Nickerson
  • 40,547
  • 20
  • 99
  • 126
10

You can do

Set<String> lines = new HashSet<String>(FileUtils.readLines(new File("foo.txt")));

Using the Apache Commons FileUtils class and the readlines method.

Zac Thompson
  • 11,873
  • 43
  • 55
Jeff Foster
  • 42,070
  • 11
  • 81
  • 103
2

Multiset can store duplicated strings, if your text contains duplicated lines. (add ordering)

Multiset<String> set = LinkedHashMultiset.create();
卢声远 Shengyuan Lu
  • 30,386
  • 22
  • 82
  • 125
0

With Apache Commons IO you have readLines which returns a List. You can then add all elements from the returned list into your HashSet (beware: type compatibility between List and Set, and loosing duplicated lines).

MarcoS
  • 13,110
  • 6
  • 39
  • 62