简体   繁体   中英

get first and last element in ArrayList in Java

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();
    }
}

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))

A simpler way to do with without lots of checks is to use seperator which is empty to start with.

StringBuilder sb = new StringBuilder();
String sep = "";
for (String s : mimeList) {
    sb.append(sep + key + "=" + s);
    sep = " or ";
}

Something like so should work: if ((i > 0) && (i < mimeList.size() - 1)) . Since in Java collections as 0 based, the first element will be at location 0 and the last will be at Collection.Size - 1 , since accessing the Collection.Size th location will cause an out of bounds exception.

From what I can gather from your question, you want something like the following:

ArrayList<Foo> foos = fooGenerator.generateFoos();

for(int i = 0; i < foos.size(); i++) {
    if(i != (foos.size() - 1)) {
        System.out.println("Front elements of ArrayList");
    }
    else {
        System.out.println("Last element of ArrayList!");
    }
}
ArrayList<int> foos = ArrayList<int>();

for the first is

foos.get(0);

for the last is

foos.get(foo.size - 1);

考虑到iArrayList.Integer ArrayList.

if ((i > 0) && (i < mimeList.size() - 1))

Try something like

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

Hope that helps!

You pretty much have the answer already in your code:

You loop from the first to the last element in your array.

first: having index 0, last: having index (size - 1)

This results in the following condition:

if ((i > 0) && (i < mimeList.size() - 1))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM