How to add the first element of a list to another list in Java

1 Answer

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

public class AddFirstElement {
    public static void main(String[] args) {
        List<String> source = new ArrayList<>();
        source.add("aaa");
        source.add("bbb");
        source.add("ccc");

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

        // Add the first element of source to target
        if (!source.isEmpty()) {
            target.add(source.get(0));
        }

        System.out.println(target);  
    }
}



/*
run:

[ddd, aaa]

*/

 



answered Oct 16 by avibootz
...