Home > Back-end >  Is there a function in Java Streams where you can get the first char for every value, in a list of s
Is there a function in Java Streams where you can get the first char for every value, in a list of s

Time:08-02

So at the moment I'm trying to learn about Java Streams for an upcoming test. One of the questions says:

Write functional code (using the streams API) that starts from a list of character strings, filters out all elements shorter than two characters, sorts the elements in alphabetical order and returns a list of the first character of each remaining character string.

I think I'm somewhat on the right path, but I can't get the "returns a list of the first character of each remaining character string." part to work.

I've gotten this far:

.streams.filter(p -> p > 1).sorted(Comparator.comparing(p -> p.toString()))

Even then I'm not sure if that's right but I'm trying to learn. So if anyone could push me to the right path I would be thankful.

CodePudding user response:

List<Character> chars = 
    strings
        .stream()
        .filter(s1 -> s1.length() >= 2)
        .sorted()
        .map(s2 -> s2.charAt(0))
        .collect(Collectors.toList());

You can use map() method to get first character for each string after applying filter and sorting. And String already implements Comparable you don't need to provide any sorting mechanism, it will be sorted in ascending order by default.

CodePudding user response:

This should answer your question. I added a null check before the string lenght check, since theoretically, if you have null strings in the input list, you will get a NullPointerException.

import java.util.stream.Collectors;

public static List<Character> fistCharAlphOrder(List<String> inputList) {
    return inputList
            .stream()
            .filter(s -> s != null && s.length() >= 2) // null check, considering strings of at least 2 chars
            .sorted() // sorting by default alphabetical order
            .map(s -> s.charAt(0)) // get the first char
            .collect(Collectors.toList()); // collect the result into a List of Character
}

CodePudding user response:

Since you said you wanted to end up with a list of character Strings I returned a List<String>. In order the steps applied are:

  • filter out strings less than two characters in length
  • sorts the allowed (filtered) strings in alphabetical order.
  • grabs the first character of each filtered string
  • and returns them in a list.
List<String> list = List.of("pineapple", "corn", "house",
        "apple", "hello", "no", "be", "if", "I", "data");

list = list.stream()
        .filter(str -> str.length() > 1).sorted()
        .map(str -> str.substring(0, 1)).toList();

System.out.println(list);

prints

[a, b, c, d, h, h, i, n, p]

CodePudding user response:

Depending on the required return type, you can use either of these.

To obtain a list of one-character strings List:

List<String> list = strings.stream()
    .filter(str -> str.length() >= 2)
    .sorted()                
    .map(str -> str.substring(0, 1))
    .toList(); // for Java 16  or collect(Collectors.toList())

To obtain a list of characters List<Character> you need to apply map() operation:

List<Character> list = strings.stream()
    .filter(str -> str.length() >= 2)   // Stream<String> 
    .sorted()                 
    .map(str -> str.charAt(0))          // Stream<Character>
    .toList(); // for Java 16  or collect(Collectors.toList())
  • Related