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));
Related
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.
I get a string form a list and try to compare it with some strings in the values and then do some stuff
for(int i=0; i<sizeOfList; i++){
String LIST_TITLE;
LIST_TITLE = list_title.get(i); //the List list_title includes some strings
if(LIST_TITLE.equals(R.string.percentbattery)) {
//do stuff
Log.d("EQUAL!","" + LIST_TITLE);
} else if(LIST_TITLE.equals(R.string.screenrecorder) == true) {
//do stuff
Log.d("EQUAL!","" + LIST_TITLE);
} else if(LIST_TITLE.equals(R.string.eightsms) == true) {
//do stuff
Log.d("EQUAL!","" + LIST_TITLE);
} else {
// do stuff
Log.e("TITLE NOT EQUAL","" + LIST_TITLE);
}
}
If I compare my LIST_TITLE with the (R.string. ...) in my Logcat they are equal, but I get only the "TITLE NOT EQUAL" Log from the else statement.
Is there another way to compare these strings? the "==" method also don't work.
R.string.percentbattery is not a String, it's an Integer that is the ID to reference the string.
what u want is:
LIST_TITLE.equals(context.getResources.getString(R.string.percentbattery))
LIST_TITLE.equals(R.string.percentbattery)
This is incorrect, because you're trying to compare string with resource ID
You should get the string from resource first:
LIST_TITLE.equals(getResources().getString(R.string.percentbattery))
R.string.xxx is an int. You need to get the String from that res
Something like
if(LIST_TITLE.equals(getResources().getString(R.string.percentbattery)))
This is assuming you have Activity Context available. Otherwise, you would need to add a Context variable in front of getResources()
R.string.some_id is just an integer by which you can get the String from the resources.
So in order to compare Strings correctly in you case you have to do:
String precentBattery = getResources().getString(R.string.percentbattery);
if (LIST_TITLE.equals (percentBattery)) ...
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.
I want check whether a String value val is contained within a List of Strings lets call it stringList.
I am doing this
if(stringList.contains(val)){
System.out.println("The value is in there");
}
else{
System.out.println("There's no such value here");
}
But it always seems to be that the value is not included. Is this because two String values that have the same characters are not actually equal? For a "home-made" class I could implement hashCode() and equals() and fix this, what can I do for String data?
EDIT:
The way I am getting val is outlined here:
List<String> stringList = new ArrayList<String>();
stringList.add("PDT");
stringList.add("LDT");
stringList.add("ELNE");
String myFile = "/folder/myFile";
InputStream input = new FileInputStream(myFile);
CSVReader reader = new CSVReader(new InputStreamReader(input), ',','"', 1);
String[] nextLine;
try {
while ((nextLine = reader.readNext()) != null) {
if (nextLine != null) {
if (nextLine[6] != null){
String val = nextLine[6];
if(stringList.contains(val)){
System.out.println("Success");
}
}
}
}
ArrayList.contains() uses Object.equals() to check for equality (hashCode() is not involved in List). This works well for strings. Probably, your string really isn't contained in the list...
You've probably overlooked some whitespace or upper/lower-case or encoding difference...
More code please!
This works:
import java.util.*;
public class Contains {
public static void main(String[] args) {
List<String> stringList = new ArrayList<String>();
stringList.add("someString");
String val = new String("someString");
if (stringList.contains(val)) {
System.out.println("The value is in there");
} else {
System.out.println("There's no such value here");
}
}
}
That doesn’t sound right: contains uses equals rather than ==, so if the string is in the list, it should be found. This can be verified in the indexOf method of the superclass AbstractList used by ArrayList.
Following your edit, make sure you trim strings before doing contains, as otherwise they may contain the newline character(s).
Try the following, first make the check more concrete by iterating the list and checking each element separately. Than, when you hit the elements that you are expecting to be equal, This is what you are supposed to be looking at. Check to see if they are really equal. Maybe there is a case difference? (or some other elusive but plain difference like white space?)
Try to override equals(){}, so that you can specify which property needs to compare equality .... :P
this is my first so I'll try to add as much info as possible so I don't get yelled at. :-)
What I am trying to do is I have 2 variables that grab text from 2 fields and take only the first character from each and assign it to those values.
This is the code that I use to get the strings. They are 2 separate calls as you would.
try { var_ContactSurname = var_ContactSurname.substring(0,1);
}
catch (Exception e){
}
I have the above again with a different variable. Now to this point it does what I want. It grabs the first letter from the fields and assigns it to the variables.
So at this point I have two variables (say with an example charater of D and R).
var_ContactSurname = R
var_ContactLicenceNumber = D
What I want to do is compare those two variables and if they match I want to return a value of TRUE, else FALSE if they don't match.
That value has to be a string as well and be assigned to a new variable called var_ContactValidate.
if (var_ContactLicenceNumber.toLowerCase().equals()var_ContactSurname.toLowerCase()){
var_ContactValidate == "TRUE";
}
else {
var_ContactValidate == "FALSE";
}
No you may notice that there might be some code missing. I am using a rules engine that does a lot of the functions for me. I can use raw Java code to do other things (like this compare)...but that's the compare that I am having a problem with.
Any ideas for that compare would be greatly appreciated.
Thanks.
i would use the String method equalsIgnoreCase()
to assign a value to a field, use a single =, not double (==).
if (var_ContactLicenceNumber.equalsIgnoreCase(var_ContactSurname){
var_ContactValidate = "TRUE";
}
else {
var_ContactValidate = "FALSE";
}
check it
In addition to what already said - a simpler & more elegant version (without the if condition) could be:
var_ContactValidate = Boolean.toString(
var_ContactLicenceNumber.equalsIgnoreCase(var_ContactSurname))
.toUpperCase();
Change your whole piece of code to:
if (var_ContactLicenceNumber.equalsIgnoreCase(var_ContactSurname)){
var_ContactValidate == "TRUE";
}
else {
var_ContactValidate == "FALSE";
}
This combines the case insensitivity that you want, and passes through the second string as an argument of the .equalsIgnoreCase function.
Also, I am not sure what you are trying to do with the line:
var_ContactValidate == "TRUE";
If you want to assign var_ContactValidate to "TRUE" then use a single equals sign '=' as a double equals '==' compares the values instead. You may also considering using a boolean rather than a string in this case.
Here is an implementation that also checks for null values and empty Strings:
public class SurnameAndLicenseValidator {
public static void main(String[] args) {
// FALSE
validateSurnameAndLicense(null, "jb78hq");
validateSurnameAndLicense("Johnson", null);
validateSurnameAndLicense(null, null);
validateSurnameAndLicense("", "jb78hq");
validateSurnameAndLicense("Johnson", "");
validateSurnameAndLicense("", "");
validateSurnameAndLicense("johnson", "xb78hq");
// TRUE
validateSurnameAndLicense("Johnson", "jb78hq");
validateSurnameAndLicense("johnson", "jb78hq");
}
private static String validateSurnameAndLicense(String surname,
String license) {
String result;
if (surname != null
&& surname.length() > 0
&& license != null
&& license.length() > 0
&& Character.toUpperCase(surname.charAt(0)) == Character
.toUpperCase(license.charAt(0))) {
result = "TRUE";
} else {
result = "FALSE";
}
System.out.println(surname + " " + license + " " + result);
return result;
}
}
The main method is used as a unit test here. You might want to extract a real JUnit test from it, if you are into that kind of thing.