Collecting adjacent cells in a 2D grid implemented as a 1D list The grid is implemented as an ArrayList&lt;Cell&gt; cells with the number of columns as int cols and int length = rows * cols. The id of a Cell is equal to its position in the list. The first element of cells is the top-left cell and the last element is the bottom-right cell.

public ArrayList&lt;Cell&gt; getAdjCells(int id) {
    ArrayList&lt;Cell&gt; cs = new ArrayList&lt;&gt;();
    //check if cell is on an edge
    boolean l = id %  cols &gt; 0;        //has left
    boolean u = id &gt;= cols;            //has upper
    boolean r = id %  cols &lt; cols - 1; //has right
    boolean d = id &lt;  length - cols;   //has lower
    //collect all existing adjacent cells
    if (l)      cs.add(cells.get(id - 1       ));
    if (l &amp;&amp; u) cs.add(cells.get(id - 1 - cols));
    if (u)      cs.add(cells.get(id     - cols));
    if (u &amp;&amp; r) cs.add(cells.get(id + 1 - cols));
    if (r)      cs.add(cells.get(id + 1       ));
    if (r &amp;&amp; d) cs.add(cells.get(id + 1 + cols));
    if (d)      cs.add(cells.get(id     + cols));
    if (d &amp;&amp; l) cs.add(cells.get(id - 1 + cols));
    return cs;
}


I may restructure ArrayList&lt;Cell&gt; cells as Cell[] cells later on. Return type can be any type of collection really. I just want this function to be as fast as possible, since I have to use it very often.
Looks good, ship it.

Certainly cols is an accurate name, but in this context sometimes people prefer to refer to it as stride.

It's close to the initial default, but still, since you know the max size you might specify a capacity: new ArrayList&lt;&gt;(8);

Modulo can be slightly expensive. Maybe you want to assign the result to a temp variable, or maybe you trust that JIT already did that for you.

The sequential memory references to {l&amp;u, u, u&amp;r} are cache friendly. The reverse sequence of addresses, {r&amp;d, d, d&amp;l} is perhaps backwards from what you prefer.