1

Is it possible to write a block of code to check all, or all objects/variables of a certain type for a certain characteristic? (Without creating an if statement for each)
Then set it to something if true or false.


Like if you had 3 variables and...

 if(a=0||b=0||c=0){
//set any variable equal to zero to 4
}

preform the action described in the comment


Or, complex example, 4 arraylists of type integer:

List<Integer> even = new ArrayList<Integer>(), //positive even ints
odd = new ArrayList<Integer>(), //positive odd ints
negaodd = new ArrayList<Integer>() //negative even ints
negaeven = new ArrayList<Integer>(); //negative odd ints

Then something like:

if("AnyArray".isEmpty()){
whatever-array-is-being-tested/tried = null;
}

So that if any of the arrays ended up being empty, then instead of [], they would return "null".

House3272
  • 1,007
  • 5
  • 14
  • 29

2 Answers2

3

Hmm, if you wanted to do something more interesting then just iteration over a collection, it does look very functional like applying a filter then map. Try out lambdaj or google collections (see here for a nice post http://codemunchies.com/2009/11/functional-java-filtering-and-ordering-with-google-collections-part-3/). Here is an example using lambdaj from https://code.google.com/p/lambdaj/wiki/LambdajFeatures.

List<Integer> oddNumbers = filter(odd, asList(1, 2, 3, 4, 5));

See here for more potential ideas: What is the best way to filter a Java Collection?

Disclaimer Sometimes going overboard with this sort of thing (when a simple loop would suffice) obfuscates the code more than anything else, so be wary.

Community
  • 1
  • 1
Anil Vaitla
  • 2,958
  • 22
  • 31
1

You could use an array or a list along with a helper method to achieve either.

int[] intArray = { a, b, c };
setZeroes(intArray);

public void setZeroes(int[] a) {
    for (int i = 0; i < a.length; i++) {
        a[i] = (a[i] == 0) ? a[i] : 4;
    }
}

Note that this won't set a, b, or c to 0, but rather the elements in the array.

But... maybe they should just be elements of an array (or List) anyways. That's my hunch.

You could do the same thing with a List of Lists.

List<List<Integer>> listOfLists = new ArrayList<List<Integer>>();
listOfLists.add(listA);
listOfLists.add(listB);
listOfLists.add(listB);
setListsToNull(listArray);

public void setListsToNull(List<List<Integer>> a) {
    for (int i = 0; i < a.length; i++) {
        List<Integer> thisList = a.get(i);
        a.set(i, thisList.isEmpty() ? null : thisList);
    }
}

I would typically use an if statement in stead of the ? operator, but you wanted no ifs....


You could easily make both methods generic (you'd have to use objects for the first example), but we'll leave that up to you....

jahroy
  • 22,322
  • 9
  • 59
  • 108