Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stream to LinkedHashSet [duplicate]

Tags:

I want to save .csv to LinkedHashSet with natural order, so the first line of the .csv should be a first element of the LinkedHashSet.

the file look like this:

java   c   c++   assembly language   swift   

and my code like this:

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());          }     } } 

but it returns incorrect order:

assembly language c++ java c swift 

I think that stream just save it as HashSet.

Is it possible to save it as LinkedHashSet with stream?

like image 515
stakowerflol Avatar asked Aug 21 '18 08:08

stakowerflol


People also ask

Is duplicate allowed in LinkedHashSet?

LinkedHashSet maintains insertion order, which means it returns the elements in the order in which they are added. It does not do any kind of sorting to the stored values. LinkedHashSet is similar to HashSet which allows only one null value in it, As duplicates are not allowed.

Does LinkedHashSet remove duplicates?

Another implementation of the Set interface is LinkedHashSet. LinkedHashSet maintains the order of elements and helps to overcome the HashSet limitation.

How do you copy all elements of ArrayList to LinkedHashSet?

Using the addAll() method of the LinkedHashSet class. Using the add() method of the LinkedHashSet class while iterating over all the elements of the ArrayList. Using stream to first convert the ArrayList to Set which is further converted to LinkedHashSet.


1 Answers

You simply don't know the specific type created by that factory method (it guarantees to return Set, nothing else).

The only reliable way is to actually control what happens, by ending the stream operation with

... collect( Collectors.toCollection( LinkedHashSet::new ) ); 
like image 56
GhostCat Avatar answered Sep 26 '22 08:09

GhostCat