How to add a range of elements of a list to another list in Java

1 Answer

0 votes
import java.util.ArrayList;
import java.util.List;

public class AddRangeToList {
    public static void main(String[] args) {
        List<String> source = new ArrayList<>();
        source.add("A");
        source.add("B");
        source.add("C");
        source.add("D");
        source.add("E");
        source.add("F");

        List<String> target = new ArrayList<>();
        target.add("G");

        // Add elements from index 1 (inclusive) to 4 (exclusive): B, C, D
        target.addAll(source.subList(1, 4));

        System.out.println(target);  
    }
}



/*
run:

[G, B, C, D]

*/

 



answered Oct 16 by avibootz
...