流到LinkedHashSet

sta*_*lol 4 java java-8 java-stream

我想用自然顺序将.csv保存到LinkedHashSet,因此.csv的第一行应该是LinkedHashSet的第一个元素.

该文件看起来像这样:

java  
c  
c++  
assembly language  
swift  
Run Code Online (Sandbox Code Playgroud)

我的代码是这样的:

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());
         }
    }
}
Run Code Online (Sandbox Code Playgroud)

但它返回错误的顺序:

assembly language
c++
java
c
swift
Run Code Online (Sandbox Code Playgroud)

我认为该流只是将其保存为HashSet.

是否可以将其保存为带有流的LinkedHashSet?

Gho*_*ica 11

您根本不知道该工厂方法创建的特定类型(它保证返回Set,没有别的).

唯一可靠的方法是通过结束流操作来实际控制发生的事情

... collect( Collectors.toCollection( LinkedHashSet::new ) );
Run Code Online (Sandbox Code Playgroud)