Category Archives: Java

Check if object is in (multidimensional) array?

Python:

>>> arr = [[1,3],[2,4]]
>>> 2 in [x[0] for x in arr]
True
>>> 3 in [x[0] for x in arr]
False

PHP:

$arr = [[1,3],[2,4]];
var_dump(in_array(1, array_map(function($x){return $x[0];},$arr), true));
var_dump(in_array(3, array_map(function($x){return $x[0];},$arr), true));

Gives

bool(true)
bool(false)

Adding true for “strict mode”, to prevent false positives (1 == true, 0 == false)

Java:

int[][] arr = {{1,3},{2,4}};
System.out.println(Arrays.stream(arr).map(x -> x[0]).collect(Collectors.toList()).contains(1));
System.out.println(Arrays.stream(arr).map(x -> x[0]).collect(Collectors.toList()).contains(3));

Gives

true
false

Converting arrays to/from strings

Found myself using these functions in various prints to interfaces and whatnot, so here’s the elegant ways of creating comma-separated strings. The added bonus is that this method allows for separation of data in for-loops. Early on I’d usually add a separation manually in each step of the loop and finish by removing the extra separation at the end.

Python:

string = ",".join(['1','2','3','4'])
array = string.split(",")

PHP:

echo($str = implode(",", [1,2,3,4,5]));
var_dump(explode(",",$str));

Java:

With Apache Commons:

StringUtils.join(new String[]{"1","2","3"}, ',');

In Android:

TextUtils.join(new String[]{"1","2","3"}, ',');

Without requires a bit of setup with StringBuilder and a for-loop, unless you use JDK8:

String[] array = {"1", "2", "3", "4", "5"};
System.out.println(String.join(",",array));

Check out the new StringJoiner class for some interesting helper functions.

Java generics and interfaces (A* example)

As part of a project where I’m building a simulator I wanted a pathfinding algorithm and looked around for an A*-library in Java. I found a few that I didn’t like the look of and decided to just make my own library. Luckily the algorithm is simple enough to basically copy-paste from the pseudocode found on Wikipedia, and it was during the rewrite I decided to really look into generics for the first time.

Below is an example of generics (note that the methods returns “T“, and not an int or string. Basically, if we send a specific object that implements AStarNode to these methods, we get an object of the same type back.

public interface AStarNode {
    public <T extends AStarNode> Collection<T> getNeighbours();
    public <T extends AStarNode> double getDistance(T node);
}

Continue reading Java generics and interfaces (A* example)