javaarraysfor-loopjava-stream

Create flattened List<String> in Java from a List and a single value


I need help on separating a List<String>.

I have a code that results to this:

List<String> inputLetters = singletonList(Arrays.asList(setOfLetters(), "f").toString()); 
[[a, b, c, d, e], f]

setOfLetters() is from a query

My question is how can I make my result like this?

[a, b, c, d, e, f]

Is it by using for loop? Or anything you can suggest.


Solution

  • For this specific problem I wouldn't try to loop through the array and solve it on this way.

    My idea would be to just add the "f" to the setOfLetters() array. On this way you could avoid unnecessary code and solve the problem by using the static value.

    Example:

    // Assuming that setOfLetters() is a Set<String> we convert it to an ArrayList<>()
    List<String> lettersSet = ArrayList<>(setOfLetters());
    lettersSet.add("f");
    

    On this way the List lettersSet would be ["a","b","c","d","e","f"].

    Also if you want to change it to a SingletonList you can just use the whole lettersSet List.