Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get first and last element in ArrayList in Java

Tags:

java

arraylist

I have small code where i have to add condition to get proper output.

if the element inside the mimeList is Last then go to else part. or to the if.

there is always 1 element in this ArrayList.

(if it has only one element then it means it is last element.)

for (int i = 0; i < mimeList.size(); i++) {
    StringBuffer sb = new StringBuffer();

    if () {
        queryString = sb.append(queryString).append(key)
        .append("=").append(mimeList.get(i)).append(" or ").toString();
    }else{
        queryString = sb.append(queryString).append(key)
        .append("=").append(mimeList.get(i)).toString();
    }
}
like image 415
GameBuilder Avatar asked Nov 30 '22 02:11

GameBuilder


1 Answers

Regarding the heading of your question:

get first and last element in ArrayList in Java

It should be pretty simple:

mimeList.get(0); // To get first
mimeList.get(mimeList.size()-1); //to get last

And regarding your if condition :

if(!(i==0 || i==mimeList.size()-1))

As you phrased it like:

if the element in mimeList is first or last it will go in else condition other wise in if condition

I used ! in if condition. Otherwise below is pretty cool:

if((i>0) && (i!=mimeList.size()-1))
like image 142
Priyank Doshi Avatar answered Mar 03 '23 16:03

Priyank Doshi