This is the third solution to list all the subsets or substrings of a given string. This approach uses functional interface with single abstract method implementation using lambda expression, the internal logic utilizes the String’s class substring method for intermediate processing of all sized sub strings.
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
//Define the functional interface with single abstract method.
interface SubsetsOfStr {
Set<String> subsets(String strVar);
}
public class SubsetsOfString {
public static void main(String[] args) {
Scanner inpStr = new Scanner(System.in);
System.out.println("Enter an input word for which you need all the sub sets of strings");
String inpWord = inpStr.next();
/*
* Define the Lambda expression for the user defined 'SubsetsOfStr' functional
* interface
*/
SubsetsOfStr ss = ((strVal) -> {
int sizeOfSubstr = 1, beginIdx = 0, endIdx = 1;
Set<String> finalSubsetStrs = new HashSet<String>();
// Iterate the loop until the substring's length is equals with length of the
// actual string
while (sizeOfSubstr <= strVal.length()) {
// Iterate the substring sized loop until the subscript less than or equals the
// actual length
while (beginIdx < strVal.length() && endIdx <= strVal.length())
finalSubsetStrs.add(strVal.substring(beginIdx++, endIdx++));
/*
* Increment size of sub string 'sizeOfSubstr' by 1, reset 'beginIdx' and assign
* next sized substring to 'endIdx' for the next iteration
*/
sizeOfSubstr++;
beginIdx = 0;
endIdx = sizeOfSubstr;
}
return finalSubsetStrs;
});
System.out.println("All the unique substrings from the given String=" + inpWord + " are below");
System.out.println(ss.subsets(inpWord));
System.out.println("All the unique substrings of another string `MIKE` are" + ss.subsets("MIKE"));
System.out.println("All the unique substrings of another string `VALLI` are" + ss.subsets("VALLI"));
inpStr.close();
}
}
Output:
Enter an input word for which you need all the sub sets of strings
JOHN
All the unique substrings from the given String=JOHN are below
[JOH, OHN, JO, HN, H, OH, JOHN, J, N, O]
All the unique substrings of another string `MIKE` are[IK, IKE, MIKE, E, I, KE, K, MI, M, MIK]
All the unique substrings of another string `VALLI` are[LL, VAL, A, ALL, VALL, VALLI, LLI, I, VA, AL, L, V, ALLI, LI]

Leave a comment