Home > Blockchain >  How to return array list which has specific char
How to return array list which has specific char

Time:03-02

i want to to return names from Array list which doesnt have char 'a' as last leterr, i tried to make loop for and find last letter from each name.

List<String> names = new ArrayList<>();
    names.addAll(Arrays.asList("Tomek", "Ania", "Krzys", "Tomek"));
   String last = names.get(names.size());
    int lastLetter = last.length() - 1;
    for (String word : names) {
        if (lastLetter != 'a' ) {
            System.out.println(names);
        }
    }
}

CodePudding user response:

List<String> toReturn = new ArrayList<>();
for (String word : names) {
    char lastLetter = word.toLowerCase().charAt(word.length() - 1);
    if (lastLetter != 'a') {
       toReturn.add(word);
    }
}
return toReturn;

CodePudding user response:

If you are using Java 8 and later you can use streams to filter the names as below.

List<String> names = Arrays.asList("Tomek", "Ania", "Krzys", "Tomek");
List<String> updated = names.stream()
                .filter(s -> s.charAt(s.length() - 1) != 'a')
                .collect(Collectors.toList());
updated.forEach(System.out::println);

In the above code names.stream() convert the array to stream and filter() will filter the stream based on the preticate the last char of string is not 'a' then the collect will create a new list with the filtered list.

  • Related