Listing last 3 items (or all if less than 3) in an ArrayList Writing a code to return the last 3 items in a list, if the list has 3 or more elements, otherwise return all list items.

But the code looks really bad.
What is a better way to write the same code?

   public void test_arrayListItems() {
        ArrayList&lt;String&gt; arrayList = new ArrayList&lt;&gt;();
        arrayList.add("item1");
        arrayList.add("item2");
        arrayList.add("item3");
        arrayList.add("item4");
        arrayList.add("item5");
        arrayList.add("item6");
        arrayList.add("item7");
        arrayList.add("item8");

        String items = "";
        int j = 0;
        int k = 0;

        if (arrayList.size() &lt;= 2) {
            j = arrayList.size() - 1;
        } else if (arrayList.size() &gt; 2) {
            j = arrayList.size() - 1;
            k = arrayList.size() - 3;
        }
        for (int i = k; i &lt;= j; i++) {
            items = items + "- " + arrayList.get(i) + " ";
        }
        logger.info(items);
    }


thanks
Is a best practice to define a variable as type of the interface the instance implement it(see OOP principles)
Just a little bit out of scope, you can declare your arrayList inline, like in the example I wrote.
Try to use available features of List(in this example) like subList rather than cycle(what if you have thousands of elements?)
toString on a list will return a string with those list, you don't have to concatenate them
it is a bad practice to concatenate strings in cycles because create new strings every time you add + " "


See an alternative solution below:

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

public class MainTest {
    public static void main(String[] args) {
        final int wantedSize = 3;
        final List&lt;String&gt; arrayList = new ArrayList&lt;&gt;(Arrays.asList("item1", "item2", "item3", "item4"));
        final int listSize = arrayList.size();
        final List&lt;String&gt; result = (listSize &gt;= wantedSize) ? arrayList.subList(listSize-wantedSize, listSize): arrayList;
        System.out.println(result.toString());
    }
}