开发者

Text file into Java Set<String> using Commons or Guava

开发者 https://www.devze.com 2023-03-01 13:52 出处:网络
I w开发者_运维知识库ould like to load each line in a file into HashSet collection. Is there a simple way to do this?How about:

I w开发者_运维知识库ould like to load each line in a file into HashSet collection. Is there a simple way to do this?


How about:

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

(using Guava).

References:

  • Files.readLines()
  • Sets.newHashSet()


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.


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

Multiset<String> set = LinkedHashMultiset.create();


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

0

精彩评论

暂无评论...
验证码 换一张
取 消