Transfer elements from one list to another using for loop in Java

nemadT :

Trying to transfer the elements of one string list to a temporary list using a for loop.

List<String> origin = Arrays.asList("foo", "bar", "var");
        List<String> temp = Arrays.asList();

        String a = null;

        for(int i = 0; i < origin.size(); i++) {
            //Want to format before adding to temp list
            a = doSomeFormatting(origin.get(i));
            temp.add(a);
        }

Keep getting an error: Exception in thread

"main" java.lang.UnsupportedOperationException
    at java.base/java.util.AbstractList.add(AbstractList.java:153)
    at java.base/java.util.AbstractList.add(AbstractList.java:111)
    at test/test.Test.main(Test.java:13)

Should this not be possible to do if for some case I want to run some formatting on the strings in the lists and transfer to a temporary list?

Darshan Mehta :

Arrays.asList returns you an immutable list, hence UnsupportedOperationException while adding. Here's the javadoc and this is what it says:

Returns a fixed-size list backed by the specified array. (Changes to the returned list "write through" to the array.) This method acts as bridge between array-based and collection-based APIs, in combination with Collection.toArray(). The returned list is serializable and implements RandomAccess.

For your case, you can actually do it without any loop with the following line (i.e. by using constructor):

List<String> temp = new ArrayList(origin);

Update

If you want to format then you can iterate and apply the format, e.g.:

List<String> temp = new ArrayList<>();
for(String element : origin) {
    String formattedElement = format(element);
    temp.add(formattedElement);
}

Here's Java 8 way:

List<String> temp = origin.stream()
    .map(e -> format(e))
    .collect(Collectors.toList());

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=143460&siteId=1