I need to do changes just on specific words

Artene Dragoş Andrei :

I have a String problem for the Java 8 streams. They want me to change all the first letter into uppercase letter just if the words aren't into "the", "a", "to", "of", "in" group.

My problem is that the filter command does delete the words from the group and I have to keep them.

I have already done the part for the upper case first letter but I have no idea how to make the "jump" over the group of words

private List<String> ignoredWords = Arrays.asList("the", "a", "to", "of", "in");
String entryParts[] = toTitlelize.split(" ");

List<String> sentenceParts = Arrays.asList(entryParts);
List<String> finalSentence = sentenceParts.stream()            
        .map(WordUtils::capitalize)
        .collect(toList());

For example :

if toTitlelize = "I love to eat pizza in my home"

It should return

"I Love to Eat Pizza in My Home"

for the moment it gives me:

"I Love To Eat Pizza in My Home"

Samuel Philipp :

You can use a simple if statement in you mapping step:

List<String> finalSentence = Arrays.stream(entryParts)
        .map(word -> {
            if (ignoredWords.contains(word)) {
                return word;
            }
            return WordUtils.capitalize(word);
        })
        .collect(Collectors.toList());

As an alternative you can use filter() and findFirst() on the ignoredWords and use an Optional:

List<String> finalSentence = Arrays.stream(entryParts)
        .map(word -> ignoredWords.stream().filter(w -> w.equals(word)).findFirst().orElse(WordUtils.capitalize(word)))
        .collect(Collectors.toList());

I also would recommend to use a HashSet instead of a List, because the words are unique and contains() is much faster:

HashSet<String> ignoredWords = new HashSet<>(Arrays.asList("the", "a", "to", "of", "in"));

The result of String.join(" ", finalSentence); will be:

I Love to Eat Pizza in My Home

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=150742&siteId=1