开发者

How to get the last three value of Arraylist

Hi How can i get last three values of list.i tried this

stringAry.get(stringAry.size()-1);

But it displays only last item of list. How can we get last three values of list. pls guide me. Is 开发者_C百科that possible to store all this three values in String array


List<String> subList = stringAry.subList(fromIndex, toIndex);


if (stringAry.size() >= 3) // Make sure you really have 3 elements
{
    List<String> array = new ArrayList<String>();
    array.add(stringAry.get(stringAry.size()-1)); // The last
    array.add(stringAry.get(stringAry.size()-2)); // The one before the last
    array.add(stringAry.get(stringAry.size()-3)); // The one before the one before the last

    System.out.println(array);
}


To make sthupahsmaht's answer complete:

List<String> subList = stringAry.subList(fromIndex, toIndex);
String[] asArray = subList.toArray(subList.size());


To get a list containing only the last 3 elements:

if ( stringAry.size() > 3 )
{
    stringAry = stringAry.subList( stringAry.size() - 3, stringAry.size() );
}


Just another possible solution:

stringAry.subList(Math.max(0, stringAry.size() - 3), stringAry.size())

Fetches the last three if the size is three or more otherwise returns all available elements.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜