Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are there any more elegant ways of handling lists in Java ? (Python VS Java)

I do like the way I can treat lists in Python. It does any recursion solution to look easy and clean. For instance the typical problem of getting all the permutations of elements in a list, in Python looks like:

def permutation_recursion(numbers,sol):
    if not numbers:
        print "this is a permutation", sol
    for i in range(len(numbers)):
        permutation_recursion(numbers[:i] + numbers[i+1:], sol + [numbers[i]])

def get_permutations(numbers):
    permutation_recursion(numbers,list())

if __name__ == "__main__":
    get_permutations([1,2,3])

I do like the way I can simple get new instances of modified lists by doing things like numbers[:i] + numbers[i+1:] or sol + [numbers[i]]

If I try to code exactly the same in Java, it looks like:

import java.util.ArrayList;
import java.util.Arrays;

class rec {
    static void permutation_recursion(ArrayList<Integer> numbers, ArrayList<Integer> sol) {
       if (numbers.size() == 0)
            System.out.println("permutation="+Arrays.toString(sol.toArray()));
       for(int i=0;i<numbers.size();i++) {
             int n = numbers.get(i);

             ArrayList<Integer> remaining = new ArrayList<Integer>(numbers);
             remaining.remove(i);

             ArrayList<Integer> sol_rec = new ArrayList<Integer>(sol);
             sol_rec.add(n);

             permutation_recursion(remaining,sol_rec);
       }
    }
    static void get_permutation(ArrayList<Integer> numbers) {
        permutation_recursion(numbers,new ArrayList<Integer>());
    }
    public static void main(String args[]) {
        Integer[] numbers = {1,2,3};
        get_permutation(new ArrayList<Integer>(Arrays.asList(numbers)));
    }
}

To create the same recursion I need to do :

ArrayList<Integer> remaining = new ArrayList<Integer>(numbers);
remaining.remove(i);

ArrayList<Integer> sol_rec = new ArrayList<Integer>(sol);
sol_rec.add(n);

Which is quite ugly and it gets worse for more complex solutions. Like in this example

So my question is ... are there any buil-in operators or helper functions in the Java API that would make this solution more "Pythonic" ?

like image 670
Manuel Salvadores Avatar asked Jan 11 '11 20:01

Manuel Salvadores


1 Answers

No.

But this is why Martin Odersky created Scala. He's even said that one of his goals for Scala is that it be the Python of the Java world. Scala compiles to Java bytecode and easily interops with Java compiled classes.

If that's not an option, you could take a look at the Commons Collection Library.

like image 159
sblundy Avatar answered Sep 24 '22 16:09

sblundy