问题
I would like to load each line in a file into HashSet collection. Is there a simple way to do this?
回答1:
How about:
Sets.newHashSet(Files.readLines(file, charSet));
(using Guava).
References:
- Files.readLines()
- Sets.newHashSet()
回答2:
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.
回答3:
Multiset can store duplicated strings, if your text contains duplicated lines. (add ordering)
Multiset<String> set = LinkedHashMultiset.create();
回答4:
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).
来源:https://stackoverflow.com/questions/5804269/text-file-into-java-setstring-using-commons-or-guava