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?
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.
Another implementation of the Set interface is LinkedHashSet. LinkedHashSet maintains the order of elements and helps to overcome the HashSet limitation.
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.
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 ) );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With