Filtering unwanted strings from an array based on a specific substring is a common task in Java programming. In this article, we will explore how to remove all strings that contain a given substring from an array using Java.
Problem statement:
Given an array of strings and a specific substring, we want to create a new array that contains only those strings from the original array that do not contain the given substring.
Approach to Solve the Problem
- Iterate through the array: Check each word to see if it contains the given substring using the
.contains()
method. - Store words that do not contain the substring: Use a list to store the filtered words.
- Return the updated list: Print the final result with only the words that do not contain the substring.
Java program to remove strings containing a substring in an Array
Here’s a Java program that implements the above approach:
package com.javacodepoint.stringarray;
import java.util.ArrayList;
import java.util.List;
public class RemoveSubstringStrings {
// Method to remove strings that contain a specific substring
public static List<String> removeStringsContainingSubstring(String[] words, String substring) {
List<String> filteredWords = new ArrayList<>();
for (String word : words) {
if (!word.contains(substring)) {
filteredWords.add(word);
}
}
return filteredWords;
}
public static void main(String[] args) {
// Example array of strings
String[] words = { "apple", "banana", "grape", "pineapple", "orange", "apricot" };
String substring = "ap";
// Remove strings containing the given substring
List<String> filteredWords = removeStringsContainingSubstring(words, substring);
// Print the result
System.out.println("Filtered words: " + filteredWords);
}
}
OUTPUT:
Filtered words: [banana, orange]
Alternative Approach (Using Java Streams)
This program uses stream()
and filter()
to remove unwanted strings and it provides a more concise and readable solution.
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class RemoveSubstringWithStreams {
public static void main(String[] args) {
String[] words = {"apple", "banana", "grape", "pineapple", "orange", "apricot"};
String substring = "ap";
List<String> filteredWords = Arrays.stream(words)
.filter(word -> !word.contains(substring))
.collect(Collectors.toList());
System.out.println("Filtered words: " + filteredWords);
}
}
Conclusion
This program efficiently removes strings that contain a given substring. Whether using loops or Java Streams, the concept remains the same. Understanding such logical problems will help you strengthen your Java skills for interviews and practical applications.
You can learn the Top 20 string array programs for interview preparation (Click here).