使用Commons或Guava将文本文件转换为Java Set

时间:2022-07-01 20:49:16

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

我想将文件中的每一行加载到HashSet集合中。有一个简单的方法吗?

4 个解决方案

#1


13  

How about:

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

(using Guava).

References:

#2


9  

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.

使用Apache Commons FileUtils类和readlines方法。

#3


2  

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

如果您的文本包含重复的行,Multiset可以存储重复的字符串。 (添加订购)

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

#4


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

使用Apache Commons IO,您可以使用readLines返回List。然后,您可以将返回列表中的所有元素添加到HashSet中(注意:List和Set之间的类型兼容性,以及丢失重复的行)。

#1


13  

How about:

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

(using Guava).

References:

#2


9  

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.

使用Apache Commons FileUtils类和readlines方法。

#3


2  

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

如果您的文本包含重复的行,Multiset可以存储重复的字符串。 (添加订购)

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

#4


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

使用Apache Commons IO,您可以使用readLines返回List。然后,您可以将返回列表中的所有元素添加到HashSet中(注意:List和Set之间的类型兼容性,以及丢失重复的行)。