Top community members
All Questions Ask Question

Welcome to Dirask IT community! ❀ đŸ’»
We are community that shares solutions with each other.

If you think you have something to add here.

you are welcome with your fresh ideas - List Articles

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 answers
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

Checkout latest Findings & News:

Checkout latest questions:

Checkout latest wiki articles:

Hey 👋
Would you like to know what we do?
  • Dirask is IT community, where we share coding knowledge and help each other to solve coding problems.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.
Read more