Share:- Whatsapp Facebook Facebook

------------------------------------- Welcome to Developerhelpway Q&A, where you can ask questions and receive answers from other members of the community.

Categories

0 votes
40 views

How to get sublist from list in java? ArrayList contains 1, 2, 3, 4, 5, 6. But i want to get only last two elements from arraylist.

in Java by

1 Answer

0 votes

See the following running code to get sublist from arraylist in java.

package com;

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

public class TestSubArrayList {
    public static void main(String[] args) {
        List<String> l = new ArrayList<String>();
        l.add("1");
        l.add("2");
        l.add("3");
        l.add("4");
        l.add("5");
        l.add("6");
        
        int le = l.size();
        int limit = 2;
        
        System.out.print("Get all data from ArrayList:");
        for(String s: l){
            System.out.print(s + ", ");
        }
        l = l.subList(le-limit, le);
        System.out.print("\nGet last 2 data from ArrayList:");
        for(String s: l){
            System.out.print(s + ", ");
        }
    }
}

Output:-
Get all data from ArrayList:1, 2, 3, 4, 5, 6, 
Get last 2 data from ArrayList:5, 6, 

by (3.1k points)
...