简体   繁体   中英

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

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?

Arrays.asList() returns an immutable list. You should use some mutable list implementation instead, such as an ArrayList :

List<String> temp = new ArrayList();

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 (ie by using constructor):

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

Update

If you want to format then you can iterate and apply the format, eg:

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());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM