EN
Java - convert Arrays.stream to LinkedHashSet
1
answers
1
points
Can I convert array of String to LinkedHashSet of String in java?
I know how I can convert it to List<String> or Set<String>, but it is not enough. I need to use uniqueness and order. So I know Set guarantees uniquness, but doesn't guarantee the order.
I also know that LinkedHashSet guarantees uniquness as it is Set and guarantee the order.
Can I convert Arrays.stream directly to LinkedHashSet?
My current code can convert only to Set<String>:
import java.util.Arrays;
import java.util.Set;
import java.util.stream.Collectors;
public class Converter {
public static void main(String[] args) {
String[] languages = {"en", "en", "de"};
Set<String> set = Arrays.stream(languages)
.collect(Collectors.toSet());
System.out.println(set); // [de, en]
}
}
Output:
[de, en]
1 answer
3
points
Hey, sure we can.
Quick solution:
import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.stream.Collectors;
public class Converter {
public static void main(String[] args) {
String[] languages = {"en", "en", "de"};
LinkedHashSet<String> set = Arrays.stream(languages)
.collect(Collectors.toCollection(LinkedHashSet::new));
System.out.println(set); // [en, de]
}
}
Output:
[en, de]
Your code almost got it right, we just need to use:
.collect( Collectors.toCollection( LinkedHashSet::new ) )
0 comments
Add comment