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

陌路散爱 提交于 2019-12-12 13:25:54

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!