我想将.csv文件以自然顺序保存到LinkedHashSet中,所以.csv文件的第一行应该是LinkedHashSet的第一个元素。
文件看起来像这样:
文件看起来像这样:
java
c
c++
assembly language
swift
我的代码看起来像这样:
public class test {
public static void main(String[] args) throws IOException {
final Charset ENCODING = Charset.forName("Cp1250");
Path fileToLoad = Paths.get("src/main/resources/test.csv");
Set<String> x = Files.lines(fileToLoad, ENCODING)
.map(Function.identity())
.collect(Collectors.toSet());
Iterator<String> it = x.iterator();
while(it.hasNext()) {
System.out.println(it.next());
}
}
}
但是它返回的顺序不正确:
assembly language
c++
java
c
swift
我认为那个流应该保存为HashSet。
使用流能否将其保存为LinkedHashSet?
Collectors.toSet()
不会使用LinkedHashSet
而只会使用HashSet
。可以尝试改用Collectors.toCollection( LinkedHashSet::new )
。 - ThomasList
结构,而不是一个无序的Set
。 - Dragonthoughts