Languages

Java - convert Arrays.stream to LinkedHashSet

1 points
Asked by:
AnnLen
1876

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 answers
3 points
Answered by:
AnnLen
1876

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
Hey 👋
Would you like to know what we do?
  • Dirask is online IT community for professionals and hobbyist to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.