Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/309.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 流到LinkedHashSet_Java_Java 8_Java Stream - Fatal编程技术网

Java 流到LinkedHashSet

Java 流到LinkedHashSet,java,java-8,java-stream,Java,Java 8,Java Stream,我想以自然顺序将.csv保存到LinkedHashSet,因此.csv的第一行应该是LinkedHashSet的第一个元素 该文件如下所示: java c c++ assembly language swift public class test { public static void main(String[] args) throws IOException { final Charset ENCODING = Cha

我想以自然顺序将.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());
         }
    }
}
我的代码是这样的:

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());
         }
    }
}
我认为该流只是将其保存为HashSet

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

返回此集合中元素的迭代器。元素不按特定顺序返回(除非此集合是提供保证的某个类的实例)


使用
List
而不是
Set

您根本不知道该工厂方法创建的特定类型(只返回Set,其他什么都不知道)

唯一可靠的方法是通过使用

... collect( Collectors.toCollection( LinkedHashSet::new ) );

一个集合通常是无序的,但有一个有序集合在存储过程中效率不高,但只保留有序和唯一的元素

检查是否可以使用此选项:

collect(Collectors.toSet())不创建
LinkedHashSet
,而是创建常规的
哈希集。

而是使用
.collect(Collectors.toCollection(LinkedHashSet::new)
来确保使用
LinkedHashSet

这是因为
Collectors.toSet()
不会使用
LinkedHashSet
而只使用
HashSet
。尝试
收集器。toCollection(LinkedHashSet::new)
取而代之。你似乎在寻找一个有序的
列表结构,而不是一个不有序的
Set
;从javadoc来看,这是一个无序的收集器。注意,OP声明他想使用
LinkedHashSet
以插入顺序对元素进行迭代。所以在这里使用Set和迭代器是可以的,he只需要使用正确的实现。@Thomas Your是对的,这以不同于OP要求的方式解决问题