In Java 8:
List<String> newList = Stream.concat(listOne.stream(), listTwo.stream())
.collect(Collectors.toList());
Java 16+:
List<String> newList = Stream.concat(listOne.stream(), listTwo.stream()).toList();
Answer from Dale Emery on Stack OverflowVideos
In Java 8:
List<String> newList = Stream.concat(listOne.stream(), listTwo.stream())
.collect(Collectors.toList());
Java 16+:
List<String> newList = Stream.concat(listOne.stream(), listTwo.stream()).toList();
Off the top of my head, I can shorten it by one line:
List<String> newList = new ArrayList<String>(listOne);
newList.addAll(listTwo);
The addAll method of ArrayList happens to work in Oracle's JDK (and OpenJDK). But it is not guaranteed to. The Javadoc for addAll says:
The behavior of this operation is undefined if the specified collection is modified while the operation is in progress. (This implies that the behavior of this call is undefined if the specified collection is this list, and this list is nonempty.)
The question is actually not as pointless as some of the answers imply. Just "trying it" is not a sufficient test that something works correctly, as this case proves.
In fact, when thinking about whether list.addAll(list) works, you need to ask yourself how it might be implemented. If it was simply iterating over list and adding each element to the end of list, you'd get a ConcurrentModificationException (or else it would go into an infinite loop). That's why the Javadoc doesn't guarantee that such a call works. As it happens, Oracle's implementation copies the passed list to an array first, and then copies each element of the array to the end of the list. This means that calling addAll for a list might not be as efficient as doing it yourself without creating an extra copy.
The main drawback with myList.add(myList); is that it won't compile, because myList isn't an Integer.
You can, however, use:
myList.addAll(myList);
Ideone demo
or
myList.addAll(new ArrayList<>(myList));
if you want to do it safely.
No, if you add at a position, it shifts everything starting at that position to the right.
So if you actually did this, you should end up with the following list:
[6, 5, 4, 3, 2, 1, 0]
Read the API: http://docs.oracle.com/javase/7/docs/api/java/util/List.html#add%28int,%20E%29
Or better yet, give it an actual try.
according to this doc on list List for Java it pushes the element to the right of the list adding one to the indices