This question already has answers here:
How do I determine whether an array contains a particular value in Java?
(30 answers)
Closed 6 years ago.
In java do we have any method to find that a particular string is part of string array.
I can do in a loop which I would like to avoid.
e.g.
String [] array = {"AA","BB","CC" };
string x = "BB"
I would like a
if (some condition to tell whether x is part of array) {
do something
} else {
do something else
}
Do something like:
Arrays.asList(array).contains(x);
since that return true if the String x is present in the array (now converted into a list...)
Example:
if(Arrays.asList(myArray).contains(x)){
// is present ... :)
}
since Java8 there is a way using streams to find that:
boolean found = Arrays.stream(myArray).anyMatch(x::equals);
if(found){
// is present ... :)
}
You could also use the commons-lang library from Apache which provides the much appreciated method contains.
import org.apache.commons.lang.ArrayUtils;
public class CommonsLangContainsDemo {
public static void execute(String[] strings, String searchString) {
if (ArrayUtils.contains(strings, searchString)) {
System.out.println("contains.");
} else {
System.out.println("does not contain.");
}
}
public static void main(String[] args) {
execute(new String[] { "AA","BB","CC" }, "BB");
}
}
This code will work for you:
bool count = false;
for(int i = 0; i < array.length; i++)
{
if(array[i].equals(x))
{
count = true;
break;
}
}
if(count)
{
//do some other thing
}
else
{
//do some other thing
}
Related
This question already has answers here:
How to check whether a List<String> contains a specific string?
(4 answers)
Closed last year.
I need help with creating a method that takes an object of the String type in the input arguments and a list of objects of the String type. The list contains forbidden words. How can I check if the String object passed to the method contains at least one of the words from the list?
public class Filter {
public static void main(String[] args) {
wordsFilter("This sentence contains a forbidden word");
}
private static void wordsFilter(String sentence) {
List<String> forbiddenWords = new ArrayList<>();
forbiddenWords.add("forbiddenWord");
forbiddenWords.add("forbidden word");
for (String word : forbiddenWords) {
if (sentence.contains(word)) {
System.out.println("The content cannot be displayed");
} else {
System.out.println(sentence);
}
}
}
}
Looks like you are missing a condition to exit the loop when a forbidden word was found:
private static void wordsFilter(String sentence) {
List<String> forbiddenWords = new ArrayList<>();
forbiddenWords.add("forbiddenWord");
forbiddenWords.add("forbidden word");
boolean doesContainAnyForbiddenWords = false;
for (String word : forbiddenWords) {
if (sentence.contains(word)) {
doesContainAnyForbiddenWords = true;
break; // leave the loop
} else {
System.out.println(sentence);
}
}
if (doesContainAnyForbiddenWords) {
System.out.println("The content cannot be displayed");
} else {
System.out.println(sentence);
}
}
You can do this easily using the Streams API
Optional<String> potential_forbidden_word =
forbiddenWords.stream().filter(word -> sentence.contains(word)).findFirst();
if(potential_forbidden_word.isPresent())
System.out.println("don't usw: "+potential_forbidden_word.get());
else
System.out.println("the sentence is clean");
you can even shorten the stream:
Optional<String> potential_forbidden_word =
forbiddenWords.stream().filter(sentence::contains).findFirst();
AS #Adriaan Koster mentioned: you can simply use the terminal operation anyMatch(Predicate):
boolean contains_forbidden_word =
forbiddenWords.stream().anyMatch(sentence::contains);
you might check for with equalsIgnoreCase() because "foo" or "Foo" or "FoO" and so on might also be forbidden.
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 4 years ago.
I am learning how to use Lists, and in my following example the switch case works but (what I deem as) the equivalent if statement does not. Can you tell me why?
public class Kapitel14 {
public static void main(String[] args) {
ArrayList<String> testList = new ArrayList<String>();
testList.add("Cousin");
testList.add("Doof");
testList.add("Dorf");
testList.add("Dortmund");
testList.add("Franz");
System.out.println(listCount(testList));
}
public static int listCount(ArrayList<String> newList) {
int capDCounter = 0;
for (String element : newList) {
String firstLetter = Character.toString(element.charAt(0));
switch (firstLetter) {
case ("D"):
capDCounter++;
break;
default:
continue;
}
//if I use this instead it returns wrong results:
//if (firstLetter == "D")
// capDCounter++;
}
return capDCounter;
}
Use
if (firstLetter.equals("D"))
capDCounter++;
instead of
if (firstLetter == "D")
capDCounter++;
.equals() method should be used here as you want to compare the values of strings.
This question already has answers here:
Get variable by name from a String
(6 answers)
Closed 4 years ago.
I would like it so that a user can tell my code that when a certain variable has a certain value it should do something. I have written a simple code sample of what I would like this to look like and I hope you can make sense of it. Is it in any way possible to make a String and let Java check wheter the variable that carries the same name is equal to the value of another variable.
int turn = 1;
String variable = "turn";
int compareToThisValue = 1;
if (variable.toVariable() == compareToThisValue) {
System.out.println("Yes it works thank you guys!");
{
I guess the following code can help. It uses java Reflection to get the job done. If you have some other requirements this can be tweaked to do so.
import java.lang.reflect.*;
class Test {
int turn = 1;
boolean checkValueVariable(String variableName, int value) throws Exception {
Field[] fields = this.getClass().getDeclaredFields();
for (Field field : fields) {
if (field.getName().equals(variableName))
return field.getInt(this) == value;
}
return false;
}
public static void main(String... args) {
Test test = new Test();
String variableName = "turn";
int variableValue = 1;
try {
System.out.println(test.checkValueVariable(variableName, variableValue));
} catch (Exception e) {
e.printStackTrace();
}
}
}
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 6 years ago.
Implement a method for adding elements to the class CacheMemory.
The Class cache memory has an array memory whose length is passed through a constructor.Elements can be added to the array only if it has not been added before and if the length of the arrays added is within the boundaries of the array.(within its length).
This is the code I came up with so far:
public class CacheMemory {
private String[] memory;
public CacheMemory(int length) {
this.memory = new String[length];
}
public void addingElementsToCache(String mem) {
for (int i = 0; i < memory.length; i++) {
if (memory[i] != mem) {
memory[i] = mem;
System.out.println(mem);
break;
} else {
System.out.println("Element already exists");
}
}
}
}
If i call this method without break,of course it will print out the string five times,but I don't want the same string to be printed out five times,I want to add five different strings and then,while loop goes through the array,and comes to element that has already been passed,to print out the message.
Actually , you need to use !string.equals("anotherString") instead of !=,since the != only compare the address of the string ,instead of the content of the string,but the method equals does it.
You got some of the logic wrong. You have to wait until you have checked all elements in the cache before you can decide that it doesn't already exist. And also, you should use .equals() for comparing Strings.
public void addingElementsToCache(String mem)
{
// Loop over slots
for (int i = 0; i < memory.length; i++)
{
if (memory[i] == null) {
// You have reached an unused slot, use it!
memory[i] = mem;
System.out.println(mem);
return;
}
else if (mem.equals(memory[i])) {
// You found a duplicate
System.out.println("Element already exists");
return;
}
}
// You have checked all positions without finding an empty slot
System.out.print("The cache was full, unable to add!");
}
If you exercise this code with
public static void main(String[] args)
{
CacheMemory cache = new CacheMemory(10);
asList("foo", "foo", "bar", "boz", "bar")
.forEach(cache::addingElementsToCache);
}
... it will print the following, which is what I think you expect:
foo
Element already exists
bar
boz
Element already exists
I have a code snippet similar to the one below,
public ArrayList getReport(reportJDOList,accountType)
{
String abc = "";
for(ReportJDO reportJDO : reportJDOList)
{
if(accountType.equals("something")
abc = reportJDO.getThis();
else
abc = reportJDO.getThat();
//somecode goes here
}
returning List;
}
As I know the value of accountType before the iteration, I dont want this check to happen, for every entry in a list as it would cause numerous number of checks if the size of reportJDOList is 10000 for an instance. How we remove this thing from happening? Thanks in Advance :)
You can indeed peform check once and implement 2 loops:
if(accountType.equals("something") {
for(ReportJDO reportJDO : reportJDOList) {
abc = reportJDO.getThis();
}
} else {
for(ReportJDO reportJDO : reportJDOList) {
abc = reportJDO.getThat();
}
}
Obviously you can improve your design by either
separating you loops into 2 different methods
Using command pattern, i.e. implementing loop body in different command and executing it to loop.
Using Guava's Function (it is just improvement of #2)
Using java 8 streams.
IF you want to save the String comparison, make it once before the loop and store the result in a boolean variable :
String abc = "";
boolean isThis = accountType.equals("something");
for(ReportJDO reportJDO : reportJDOList) {
abc = isThis ? reportJDO.getThis() : reportJDO.getThat();
//somecode goes here
}
I'd vote for clean coding this - perform the check once and delegate the logic into private methods, each performing the loop individually. This duplicates code for the loop but gives greatest flexibility if at some point you need to do something more in SomethingReport that's not duplicated in OtherReport.
public ArrayList getReport(reportJDOList,accountType) {
if("soemthing".equals(accountType)) {
return getSomethingReport(reportJDOList);
} else {
return getOtherReport(reportJDOList);
}
}
private ArrayList getSomethingReport(reportJDOList) {
[...]
}
interface AccountHandler {
String get(Report r);
}
AccountHandler thisHandler= new AccountHandler() {
#Override
public String get(Report r) {
return r.getThis();
}
};
AccountHandler thatHandler= new AccountHandler() {
#Override
public String get(Report r) {
return r.getThat();
}
};
//...............
AccountHandler ah;
ah = (what.equalsIgnoreCase("this")) ? thisHandler : thatHandler;
Report r=new Report();
// loop
ah.get(r);
//Using reflection:
Report r = new Report();
Method thisMethod = r.getClass().getDeclaredMethod("getThis");
Method thatMethod = r.getClass().getDeclaredMethod("getThat");
Method m = (what.equalsIgnoreCase("this")) ? thisMethod : thatMethod;
m.invoke(r);