If i have 5 optional parameters that be passed by GET API call how can i filter the array of JSON and get desired results.
Basically if all 5 parameters are passed i can check in an 'ANDED' IF statement as follows
if (obj.get(address).toString().contains(searchRequest.getAddress())
&& obj.get(car).toString().equalsIgnoreCase(searchRequest.getCar())
&& properties.get(name).toString().equalsIgnoreCase(searchRequest.getName())
&& properties.get(job).toString().equalsIgnoreCase(searchRequest.getJob())
&& properties.get(salary).toString().equalsIgnoreCase(searchRequest.getSalary())
searchRequest contains 5 fields which can optional be passed to GET REST call which will work fine, but if only two fields are passed which is allowed how can i build up correct ANDED IF statement so for example if only searchRequest.getAddress() and searchRequest.getName() are passed i would want
if (obj.get(address).toString().contains(searchRequest.getAddress())
&& obj.get(name).toString().equalsIgnoreCase(searchRequest.getName())
and ignore the other 3 fields
Use a comparison method:
public static <T> boolean equalsIgnoreCase(T a, T b) {
if (a == b) {
return true;
} else if (a == null || b == null) {
return false;
} else {
return a.toString().equalsIgnoreCase(b.toString());
}
}
Related
I am using Talend to filter out some rows from an excel file and they don't allow block statements. Everything has to be simple logic or using the ternary operator. So the problem is that the code/logic I need will be used across every cell in the column, BUT some of the cells are null, some are Strings and the rest are Strings that represent integers.
My logic needs to be this:
Return true if and only if PlanName == null || PlanName == 0 but as you can tell, it will fail when it tries to run this on a cell that contains the null or the cell that contains a String that isn't a number.
Is it possible to have this logic in java without the try-catch or block statements? This is what I have right now:
input_row.PlanName == null || Integer.parseInt(input_row.PlanName) == 0
Thanks!
Edit: Basically, I just need to write logic that does this:
Return true if input_row.PlanName == null OR if input_row.PlanName == 0
This needs to be done without using block-statements or try-catches because I am using Talend. So I can only use logical operators like && and || and I can use ternary operators as well.
In your situation, i'll go for routines : reusable bunch of code, handy for this kind of rules that would be hard to implement without if/else etc.
You can create two Routines in Talend, with static methods that you would be able to use in a tMap or a tJavaRow.
First Routine to know if your plan is a numeric or not :
public static boolean isNumeric(String strNum) {
if (strNum == null) {
return false;
}
try {
double d = Double.parseDouble(strNum);
} catch (NumberFormatException nfe) {
return false;
}
return true;
}
Then another routine like :
public static boolean correctPlanName(String planName) {
if(Relational.ISNULL(planName)){
return false;
}
else{
if(!isNumeric(planName)){
return false;
}
else {
return true;
}
}
}
Then you call Routines.correctPlanName(input_row.planName) in tMap/tJavaRow.
It should do the trick.
You can use a regular expression to check if the String only contains digits, then check if num == 0.
input_row.PlanName == null || (input_row.PlanName != null && input_row.PlanName.matches("\\d+") && Integer.parseInt(input_row.PlanName) == 0)
Edit: Probably overkill but to cover other cases e.g. floating point types, numbers prefixed with +/-, you could also do:
input_row.PlanName != null && input_row.PlanName.matches("[-+]?\\d*\\.?\\d+") && Double.parseDouble(input_row.PlanName) == 0)
I'll be receiving an HTTP URL with three input parameters. In that one of the parameter is a string and other two of integer values.
I want to check whether all three request parameters are present or not. Also, I need to check all the input parameters is null or not..
Example - http url:
http: //....../a=123456&b=12345678&c=y
String a = request.getParameter("a");
String b = request.getParameter("b");
String c = request.getParameter("c");
if(a != null && !a.isEmpty()) {
//Do something with a.
}
if(b != null && !b.isEmpty()) {
//Do something with b.
}
if(c != null && !c.isEmpty()) {
//Do something with c.
}
If the request parameter is not present it will be null. If it is present but has no data set, it will be an empty string.
I am new to Java. I am facing an issue now in which I couldn't find the easiest and cleanest way of solving it.
Suppose I have 3 parameters(string) passed to a function(could be a Hashmap too).I want to check if individual variable or combination of variables is not Null and act accordingly.
For example one way to do this is using if-else this way
if(a!=null && b == null && c == null) {
//doSomething
}
else if(a==null && b!= null && c == null ) {
//doSomething
}
else if(a==null && b0= null && c != null) {
//doSomething
}
......
//Similarly combination of two variables
if(a!=null && b != null && c == null) {
//doSomething
}
else if(a!=null && b== null && c != null) {
//doSomething
}
else if(a==null && b!= null && c != null) {
//doSomething
}
......
//and so on
//Similarly combination of three variables
if(a!=null && b != null && c != null) {
//doSomething
}
....
How to achieve this kind of situation. I found similar question, but didn't make the code clean. Any help will be appreciated
Write these utility functions and you can compare n terms easily.
public static boolean areAllNull(Object... objects) {
return Stream.of(objects).allMatch(Objects::isNull);
}
public static boolean areAllNotNull(Object... objects) {
return Stream.of(objects).allMatch(Objects::nonNull);
}
you can use these functions for n comparisons.
if(areAllNotNull(a) && areAllNull(b,c)) {
//doSomething
}
else if(areAllNotNull(b) && areAllNull(a,c)) {
//doSomething
}
else if(areAllNotNull(c) && areAllNull(b,a)) {
//doSomething
}
This is my solution. Note, that you have multiple if...else in one single method. And then you add doSomething. This is going to be terrible to ready and later to realize.
What about to move one single condition into separate method and name it with relative name. Then, lets encapsulate it into Consumer and all of it into a predefined list. Later, if your doSomething will be huge, then you can move from single method to single class, not modifying client code.
This is class, to collect required variable for conditions:
final class Data {
private final String a;
private final String b;
private final String c;
}
Then define one Consumer per on if statement:
Consumer<Data> wonderfulConsumer = data -> {
if (a != null && b == null && c == null) {
// do something for wonderful consumer
}
};
Consumer<Data> badLuckConsumer = data -> {
if (a == null && b != null && c == null) {
// do something for bad luck consumer
}
};
Note, all these consumers could be modified separately (even be in the different classes).
Then in the client code, define list of all known consumers: List<Consumer<Data>> consumers = Arrays.asList(wonderfulConsumer, badLuckConsumer).
And finally your method will be like this and you do not need to change it when you decide to modify or add consumers.
Data data = new Data(a, b, c);
consumers.forEach(consumer -> consumer.accept(data));
If I had to do this , i will do it in the same way that you have done.
but if you dont like that and if you think it is not readable you can do it in this way, i expect lot of negative comments to this answer because this is a bad solution.
public static void yourMethod(Object a,Object b,Object c)
{
int evaluation = howManyNotNull(a,b,c);
if(evaluation == 0) // all are nulls
{
// your code
}
else if(evaluation == 1) // only one is not null
{
if(a!=null)
{
}
else if(b!=null)
{
}
else
{
// c not null
}
}
else if(evaluation == 2) // two variables are not null but other one is null
{
if(a==null)
{
}
else if(b == null)
{
}
else
{
// c is null, a and b not null
}
}
else
{
// all abc not null
}
}
private static int howManyNotNull(Object a, Object b, Object c)
{
return (a==null?0:1) + (b==null?0:1) + (c==null?0:1);
}
There is extended version of this , assign 3 prime values for a, b , c (example :a=2,b=3,c=5), then use a supportive method like this
private static int convertAvailabilityToInt(Object a, Object b, Object c)
{
return (a==null?1:2) * (b==null?1:3) * (c==null?1:5);
}
if the answer is 1 ,then all are not null .
You can use for example a 3 digit string simulating 3 flags.
You first set it to "000".
Then you check each variable for null, if it is not you will replace the 0 with 1.
Then you could use switch cases to treat each case.
You are doing everything right but you have to remember that primitive data types cannot be null. For example string is not null, but empty string "", or int cannot be null, its by default sets to 0. In conclusion Objects like Map , ArrayList or Integer.. you can check for null, but primitive data types cannot be null, so you cannot check them for it. For deeper understanding just learn about primitive and advanced data types.
I hope I got your problem right :)
I am currently trying to implement a binary search tree shape comparison and am having trouble with one line of my code.
if(treeStructOne.getHeight() == 1 && treeStructTwo.getHeight() == 1) //Base Case, if both are empty then they must be equal!
{
return true;
}
if(treeStructOne.getHeight() != treeStructTwo.getHeight()) //First make sure height is the same, if not, must be unequal
{
return false;
}
if(treeStructOne.hasLeft() && treeStructTwo.hasLeft())
{
return similar(treeStructOne.getLeft(),treeStructTwo.getLeft());
}
if(treeStructOne.hasRight() && treeStructTwo.hasRight()) //PROBLEM IS HERE
{
return similar(treeStructOne.getRight(),treeStructTwo.getRight());
}
return false;
The problem occurs when a node on Tree 1 and 2 has a left child, but only tree 1 has a right and not Tree 2. After it checks that they both have left children, it does not run the the check on right children if left is true. Is this to do with the way recursion works in java?
if both trees hasLeft() returns true then your method will return in that if clause. My guess is you want to assign the result from the similar call in the last two if clauses and after the if clause do something like
return leftSimilar && rightSimilar;
The first two if's will work, but the last part should capture the conditions of p implies q which is ~p or q for both left and right. In other words, if treeStructOne has a left subtree and treeStructTwo has a left subtree, then check to see if they are similar (return similar...)
if(treeStructOne.getHeight() == 1 && treeStructTwo.getHeight() == 1) //Base Case, if both are empty then they must be equal!
{
return true;
}
if(treeStructOne.getHeight() != treeStructTwo.getHeight()) //First make sure height is the same, if not, must be unequal
{
return false;
}
return (treeStructOne.hasLeft() && treeStructTwo.hasLeft()
? similar(treeStructOne.getLeft(),treeStructTwo.getLeft())
: false)
&& (treeStructOne.hasRight() && treeStructTwo.hasRight()
? similar(treeStructOne.getRight(),treeStructTwo.getRight())
: false);
The return statement immediately returns from the current method, i.e. the remainder of the method will not be executed.
In your case, you want to make two recursive calls before returning from the method. You can do this with:
boolean similarLeft;
if(treeStructOne.hasLeft() && treeStructTwo.hasLeft()) {
similarLeft = similar(treeStructOne.getLeft(),treeStructTwo.getLeft());
} else {
similarLeft = ?; // TODO what is good condition here?
}
then do the same for the right side and conclude with
return similarLeft && similarRight;
However, for truly ideomatic java, I'd do the null checks after invoking the method rather then before it, thereby reducing code duplication:
boolean similar(TreeStruct x, TreeStruct y) {
if (x == null) {
return y == null;
} else {
return y != null && similar(x.left, y.left) && similar(x.right, y.right);
}
}
I have a function which accepts two parameters, foo(A a, String type) depending on type I have to change the if statement condition.
foo(A a, String type){
//if type equals 'bar'
if(!a.isEmpty() && a.hasMember()){...}
//but if type is something else
if(!a.isEmpty() || a.hasMember()){...}
}
the logic in the if body is the same pretty much everything else is the same except the condition is there any efficient way to implement the difference or I have to write everything twice?
I suppose you can use the following:
foo(A a, String type){
//if type equals 'bar'
if("bar".equals(type)) {
if(!a.isEmpty() && a.hasMember()){...}
}
else {
//but if type is something else
if(!a.isEmpty() || a.hasMember()){...}
}
}
Explanation: If type has value "bar" then if condition becomes true and then whatever code you want for that condition will be executed.
You can also use concise form:
if( ("bar".equals(type) && (!a.isEmpty() && a.hasMember())) || (!"bar".equals(type) && (!a.isEmpty() || a.hasMember()))) {
// Do your stuff
}
The point to note is "bar".equals(type) is better than type.equals("bar") as it also saves you from hassle of the case when type is null.
Combine the predicates with an || and make the check of type in each condition part.
if (type.equals("bar") && !a.isEmpty() && a.hasMember()) || (!type.equals("bar") && (!a.isEmpty() || a.hasMember())) {
//do your thing
}
If null is a possible value of type, then it is possible to change the check to "bar".equals(type) to avoid a NullPointerException.
You could use a map with key type, and value should be object that have you type related logic.
foo(A a, String type) {
typesMap.get(type).execute(a);
}
class TaskImpl implements Task { // each task should behave as it should be
#override
public void execute(A a) {
if(!a.isEmpty() && a.hasMember()) {...}
}
}