Learn java 8 program to find words longer than 5 characters and convert to uppercase using Stream filter() , map(), and Collectors.toList() .
Code Explanation (Step-by-Step)
• Create a string array that contains multiple string values.
• Arrays.stream(strArray) converts the string array into a Stream .
• filter(word -> word.length() > 5) checks each word and selects only those whose length is greater than 5.
• map(String::toUpperCase) converts each filtered word into uppercase letters.
• collect(Collectors.toList()) stores all filtered and uppercase words in a new List.
• Finally, print the list of words.
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class FindWord {
public static void main(String[] args) {
String[] strArray = { "Mumbai", "Delhi", "chennai", "pune", "punjab", "goa" };
List words = Arrays.stream(strArray)
.filter(word -> word.length() > 5)
.map(String::toUpperCase)
.collect(Collectors.toList());
System.out.println("Words are: " + words);
}
}
Output :
Words are: [MUMBAI, CHENNAI, PUNJAB]
Java 8 Program to Find Words Longer Than 5 Characters
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class FindWords {
public static void main(String[] args) {
String[] strArray = { "Mumbai", "Delhi", "chennai", "pune", "punjab", "goa" };
List words = new ArrayList<>(Arrays.asList(strArray));
words.removeIf(word -> word.length() <= 5);
System.out.println("Words are: " + words);
}
}
Output :
Words are: [mumbai, chennai, punjab]
FAQ
How do you find words longer than 5 characters in Java 8?
You can use the Java 8 Stream filter() method with the condition word.length() > 5.
How do you convert words to uppercase in Java 8?
You can use the map() method with String::toUpperCase.
Which Java 8 methods are used in this program?
This program uses stream(), filter(), map(), and collect() methods.
Why is Collectors.toList() used?
Collectors.toList() is used to collect the filtered and converted words into a List.