After reading some other similar questions, I found that you cannot use a switch statement to check for more than one .contains tasks that result in different outcomes. I don't want to keep repeating if(string.contains("") for a single string. How else can I minimize the amount of .contain statements or is there actually a way I can implement a switch?
Using for loop to iterate through words to archive multiple .contains check.
First, create a class that validates your string input.
public class StringValidator {
String[] words = new String[]{"apple", "banana", "orange"};
public boolean isMatchAll(String input) {
for (String word : words) {
if (!input.contains(word)) {
return false;
}
}
return true;
}
}
Then call StringValidator.isMatchAll to check whether your string input is match all words
StringValidator stringValidator = new StringValidator();
String input = "I like apple, banana and orange.";
boolean isMatch = stringValidator.isMatchAll(input); // true
You could use a switch statement, but it would need to be paired with a loop that cycles multiple times for each word that needs to be matched.
Consider the following code that does the same thing, but with only a single contains statement written in code. The trick is that we simply create a list of words that need to be matched, and we pass your string and those words into a helper method which returns true if all the words matched:
//Sample list of words to match
String[] words = new String[]{"some", "example", "words"};
//Sample text to check
String yourText = "This is an example of some words to check for";
//Now we call our helper method containsList(yourText, words)
if (containsList(yourText, words)){
System.out.println("All words found");
}
else{
System.out.println("Not all words found");
}
And the following helper method is all the code we need, it simply uses a for loop to check each word and return true of false:
public static boolean containsList(String yourText, String[] listOfWords){
for (String word : listOfWords)
{
if(yourText.contains(word) == false)
//Break as soon as a match is not found
return false;
}
//Return true if all words in the words list were found
return true;
}
The result from our sample text is true and will print out "All words found".
Note that this may not a very efficient solution for large data sets, but you have not indicated in your question that you are working with large data, and this will work just fine in most cases.
Related
I am currently working on when a user input a string, then my program will return the search result based on the inputted string. (In this example is "ca")
In the code below, I am only manage to make my program to return all the results which contains lowercase "ca" only.
However, I would like to convert "ca" to all Upper Case while still performing "contains" Regex when returning the search result. Which means, no matter the case is "ca" or "CA", all the results which conatins "CA" will be returned.
May I know how should I modify the code below? Thanks in advance.
public boolean matches( courseList p )
{
return p.getName().contains("ca");
}
Just change your whole text to lower/upper case:
public boolean matches( courseList p )
{
return p.getName().toUpperCase().contains("CA");
}
or
public boolean matches( courseList p )
{
return p.getName().toLowerCase().contains("ca");
}
There is this problem that i have been stuck with for hours.
I'm trying to check an ArrayList for a specific String.
This is the ArrayList i am checking:
public ArrayList getAllowedPlayers() {
return this.allowedPlayers;
}
The username's get added in lower case to this list.
Then this is what i use to check if the player typing the command is on the list:
boolean addedToSSList = data.getAllowedPlayers().contains(astring[0].toLowerCase());
"data" refers to the ArrayList of the username that has been entered (astring[0]). Which is in another class.
Then i use a print to chat message to check if the boolean turns true or false, which always returns false in my case.
icommandsender.sendChatToPlayer("addedToList: "+addedToSSList);
However, i can see that the username entered is added to the list with:
icommandsender.sendChatToPlayer("Allowed players: "+data.getAllowedPlayers())
The player from icommandsender is the person using the command to see if he is on the ArrayList.
So basically:
I can see that the Username i am entering is on the ArrayList (in lowercase). The astring[0] is this username in lowercase that i entered. But my boolean method will still return false.
Try this:
boolean addedToSSList = data.getAllowedPlayers().contains(astring[0].toLowerCase().trim());
May be you have some trailing spaces in your string.
EDIT:
public boolean findString(String s, ArrayList<String> al){
for (String str : al){
if (str.equalsIgnoreCase(s)){
return true;
}
}
return false;
}
and then you can find like
findString("myString", yourArrayList);
Is it possible to get multiple strings with .equals?
if(something.equals("String1 String2 String3")){
System.out.println(Something);
}
What I mean is:
if(choose.equals("DO IT")){
sysout blah blah blah
}
else if(choose.equals("DONT DO IT")){
...
}
No, but an alternative for many strings is to put the strings in a collection and do something like:
Set<String> strings = new HashSet<>();
strings.add("A");
strings.add("B");
strings.add("C");
if (strings.contains("D")) {
// ...
}
which is perhaps a little more concise. It's also null-safe wrt. the string you're looking to compare, which is often very useful.
Note further with Java 7 the switch statement works with strings, and that's useful if you wish to tie different actions to different strings.
If something is "String1 String2 String3" then it is equal.
If you mean contains, you can do
List<String> valid = Arrays.asList(string1, string2, string3);
if (valid.contains(something))
No you cannot. equals() takes only one object at a time.
As an alternative, you can try something like
if(something.equals("String1") || something.equals("String2") ||
something.equals("String3")) {
System.out.println(Something);
}
If you mean "can I test a string being equal to several strings in one operation", use regex:
if (something.matches("String1|String2|String3")) {
System.out.println(Something);
}
The pipe char | means "OR" in regex.
Note that in java (unlike many other languages) matches() must match the whole string - ie this is an "equals" comparison, not a "contains" comparison.
You can use a regex given the strings you match don't contain special regex characters, or are escaped.
Example:
Pattern p = Pattern.compile("^(String1|String2|String3)$");
if(p.matcher(something).find()) {
//do something
}
Or you can store the strings in a set/list and query the set:
Example:
HashSet<String> possible = new HashSet<String>();
possible.add("String1");
possible.add("String2");
possible.add("String3");
if(possible.contains(Something)) {
//do something
}
No, but you can use || to test multiple strings for equality:
if(something.equals("String1") || something.equals("String2") || something.equals("String3"))){
System.out.println(Something);
}
If you have gone through the javadocs it says
public boolean equals(Object obj); :
Indicates whether some other object is "equal to" this one.
It does not says that some other object is "equal to" these Objects.
Using equals() you can compare an Object with some other Object. It does not allow you to compare at once an Object with many other Objects. However if you want to compare an Object with many other Objects then you will need equals() for each comparasion
Well, if you want to check if there are any in such a string that don't match (aka all must match, albeit that doesn't really seem to make sense to me), then
String initString = "String1 String2 String3";
String[] splitStrings = initString.split(" ");
boolean match = true;
for(String string : splitStrings)
{
if(!string.equals(something))
{
match = false;
break;
}
}
if(match == true)
{
//did match all of them
}
else
{
//there was one that was not matched
}
If you want a "matches at least one" then it's just
String initString = "String1 String2 String3";
String[] splitStrings = initString.split(" ");
boolean match = false;
for(String string : splitStrings)
{
if(string.equals(something))
{
match = true;
break;
}
}
if(match == true)
{
//did match at least one of them
}
else
{
//didn't match any of them
}
But to be honest, Java 8 makes this simpler:
String something = "whatever";
String initString = "String1 String2 String3";
String[] splitStrings = initString.split(" ");
boolean matchAll = Arrays.stream(splitStrings).allMatch((x) -> x.equals(something));
boolean matchAny = Arrays.stream(splitStrings).anyMatch((x) -> x.equals(something));
This is a method in a spell checker. As the header explains, it should return true if and only if all the words added to the arraylist are found in the parent array, words. Otherwise it should return a false value. I've been fighting with this for a few hours and this is my current situation...
/**
* This method returns true if (and only if) all words in the
* given wordList are found in the dictionary.
*/
public boolean allKnown(ArrayList<String> wordList)
{
boolean result = true;
for(int index = 0; index < wordList.size(); index++)
{
if(words.contains(!wordList.contains(index)))
{
result = false;
}
result = true;
}
return result;
}
All I really need is a way to turn out a yes or no, but I'm lost.
Please try and work with the code given as this is an exercise to teach that code.
Thanks!
Your problem is here:
if(words.contains(!wordList.contains(index)))
!wordList.contains(index) is a boolean expression, so it always evaluates to either true or false. So you're actually checking if the words list contains true or false, not the word like you want. Replace it with if(!words.contains(wordList.get(index)) to check if the current word is found in the dictionary.
I would suggest a following solution: iterate wordList word by word, and for each word check if it's found in the dictionary. If not so, return false immediately. If you reach the end of the loop, return true.
Here could be another solution:
public static boolean allKnown(List<String> parent, List<String> child) {
List<String> temp = new ArrayList<String>(child);
temp.removeAll(parent);
return temp.isEmpty();
}
For example:
List<String> parent = Arrays.asList("w1", "w2", "w3", "w4");
List<String> childOk = Arrays.asList("w1", "w4");
List<String> childKo = Arrays.asList("w1", "xx");
System.out.println(allKnown(parent, childOk));
System.out.println(allKnown(parent, childKo));
Prints:
true
false
Take out result = true; - you don't want to reset the value to true at every step in the loop.
Also change wordList.contains to wordList.get (because you want to get the word at a specific index, not check if it's contained in wordList) and move the ! out (because you can't 'not' a string).
And you can also optimize by checking result's value in the for-loop condition (or simply returning directly in the if-statement).
public boolean allKnown(ArrayList<String> wordList)
{
boolean result = true;
for(int index = 0; index < wordList.size() && result; index++)
{
if(!words.contains(wordList.get(index)))
{
result = false;
}
}
return result;
}
If words really is an array and not an ArrayList, it doesn't have a contains method, you'll have to either have a double for-loop, or convert it to a list:
List<String> parentWords = Arrays.asList(words);
...
if (parentWords.contains(...))
Don't reset result to true after your if. Because like this the whole function will always return true.
A few tips:
Don't use ArrayList as a method parameter, always use the more abstract List (none of your code depends on ArrayList, so you can change the implementation later, if you like).
Iterate over List objects using the simplified syntax shown below.
You only need one word to be not in the words list to return false, so do exactly that (as shown below).
public boolean allKnown(List<String> wordList) {
for (String word : wordList) {
if (!words.contains(word)) {
return false;
}
}
return true;
}
public boolean allKnown(ArrayList<String> wordList)
{
boolean result = true;
for(String word : wordList)
{
if(!words.contains(word))
{
result = false;
}
}
return result;
}
Here is a simpler version :
public boolean allKnown(List<String> wordList) {
List<String> wordListCopy = new ArrayList<String>(wordList);
return !wordListCopy.retainAll(words);
}
PS : retainAll() removes from you wordList all of its elements that are not contained in you dictionnary. This method return true if your wordList changed as a result of the call (after removing the non existing element), in other word, this method return false when all your wordList elements exists in you dictionnary.
I'm having ArrayList Contains of String. I would like to check whether the character is present in the arraylist. I'm using the following code.
if(list.toString.contains(char))
{
// enter code here
}
Can i use this toString() method. What is the drawback?
It would be a really bad idea to use List.toString() and search that. Your code should probably look something like this :
Iterator it = list.getIterator();
char searchChar = 'S';
while (it.hasNext())
{
String s = (String) it.next();
if ( s.contains(searchChar) )
{
//Found the char!
}
}
No you cannot go ahead with arraylist.toString(), as it will not provide string representation of contents in String.
Better approach is to iterate over list and check, as below.
for(String detail:listString){
if(detail.contains('X')) //replace 'X' with your character
{
// do somethng
}
}
Try this,
Arrays.toString(inputList.toArray()).contains(searchValue);
list.toString() gives you a string representation of a list and thus it contains more characters then just the concatenated list elements
[stringElement1, stringElement2, ... ]
Therefore your approach will not work if the character you are looking for is , , , [ or ].
And keep in mind that this string representation is implementation specific. It might not work for other list implementations than ArrayList
I would recommend to write a method linke this:
private boolean listElementContains(List<String> list, String subString){
for(String element : list){
if(element.contains(subString)){
return true;
}
}
return false;
}
You can call toString() on any Java Object. List is an Object which contains (you guessed it) a list of other Objects. Therefore, you can also call toString() on each Object contained within the List. You should read about inheritance in Java.
In your particular case, you have a List of Strings. What you actually want to do is check each String in the List to see if the String contains a particular character. Topics you may want to read about include iteration, for loops, and for each loops.
If I understand this correctly, your code would look like this:
List<String> strings = new ArrayList<>();
//add strings to list
for (String string : strings) {
//Look for some character c
if (string.indexOf(c) >= 0) {
return true;
}
}
return false;
On the matter of list.toString, that simply returns a representation of the object as a string; it has nothing to do with the contents. Think of it like a label on a box of stuff that says "Junk." The box is labeled Junk, but you have no idea what's in it.
What's nearly certain is that toString will return a nonsense label for the object in memory. So to get at what's inside, you need to loop through the contents as shown above.
if(list.toString.contains(char))
String's contains() method won't take char as param, instead check with indexOf
Your code works, with little modifications.
A small example here:
List<String> list= new ArrayList<>();
list.add("test");
list.add("test2");
if (list.toString().indexOf('t') > -1) // True
{
System.out.println("yes there");
}
Note:
As a workaround, Make an char array and add your char in to that array and then use contains method.