CamelCase pattern matching in Java
In this tutorial we are going to learn about CamelCase pattern matching in Java. In this a list of CamelCase words will be there and a pattern will be there. So, we will be printing all the strings in that list matching that pattern. For example: –
array[]=[“CodeSpeedy”,”CodeSpeedyJava”,”CodeBlog”] and the pattern is “CS”. So, our code will print CodeSpeedy and CodeSpeedyJava.
So, we are going to follow certain steps: –
- We will be creating a hashmap.
- This HashMap will contain each word and it’s corresponding Uppercase letters as a string.
- After that we will match these Uppercase string with the pattern and print the corresponding word.
CamelCase Implementation
Now we are going to implement our code using Java.
Code: –
import java.util.*;
class Main{
//Function that takes List of words and a pattern
static void PatternMatcher(ArrayList<String> word, String camelPattern) {
//Creating map of UpperCase letter and words
Map<String, List<String>> ucmap = new HashMap<String, List<String>>();
//Mapping words and their corresponding Uppercase string
for (int i = 0; i < word.size(); i++) {
String s = "";
int length = word.get(i).length();//Length of each word
for (int j = 0; j < length; j++) {
//If our letter is Uppercase then we add that letter to the string s and map it to our word
if (word.get(i).charAt(j) >= 'A'&& word.get(i).charAt(j) <= 'Z') {
s += word.get(i).charAt(j);
ucmap.put(s,list(ucmap.get(s),word.get(i)));
}
}
}
boolean wordpresent = false;
for (Map.Entry<String,List<String>> mp : ucmap.entrySet()) {
if (mp.getKey().equals(camelPattern)) {
//if our key matches our pattern then word present is true and we print the corresponding string
wordpresent = true;
for(String s : mp.getValue()) {
System.out.print(s +"\n");
}
}
}
//If No word matches our pattern then we print this
if (!wordpresent) {
System.out.println("No such word found with the corresponding pattern");
}
}
//Function to add as list
private static List<String> list(List<String> list, String str) {
List<String> temp = new ArrayList<String>();
if(list != null)
temp.addAll(list);
temp.add(str);
return temp;
}
public static void main(String[] args)
{
String word[] = {"No", "NoProblem", "NotPossible", "NotPos", "NewPosition"};
ArrayList<String> givenList = new ArrayList<String>(Arrays.asList(word));
String camelCasePat = "NP";
PatternMatcher(givenList, camelCasePat);
}
}
Output: –
NoProblem NotPossible NotPos NewPosition
This is how we do CamelCase pattern matching.
Also Read: –
Leave a Reply