I would like to load each line in a file into HashSet collection. Is there a simple way to do this?
Asked
Active
Viewed 8,520 times
4 Answers
14
How about:
Sets.newHashSet(Files.readLines(file, charSet));
(using Guava).
References:

Simon Nickerson
- 42,159
- 20
- 102
- 127
-
With static imports this becomes `newHashSet(readLines(file, charSet));` – Ray Apr 27 '11 at 13:11
11
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
- 12,401
- 45
- 57

Jeff Foster
- 43,770
- 11
- 86
- 103
-
`readLines` method is deprecated, use `readLines(File, Charset)` instead – Vinit Solanki Mar 04 '19 at 07:03
2
Multiset can store duplicated strings, if your text contains duplicated lines. (add ordering)
Multiset<String> set = LinkedHashMultiset.create();

卢声远 Shengyuan Lu
- 31,208
- 22
- 85
- 130
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,386
- 7
- 42
- 63