反转数组列表的最简单方法是什么?

时间:2022-05-02 11:49:51

What is the simplest way to reverse this ArrayList?

反转这个数组列表的最简单方法是什么?

ArrayList aList = new ArrayList();

//Add elements to ArrayList object
aList.add("1");
aList.add("2");
aList.add("3");
aList.add("4");
aList.add("5");

while (aList.listIterator().hasPrevious())
  Log.d("reverse", "" + aList.listIterator().previous());

9 个解决方案

#1


666  

Collections.reverse(aList);

Example (Reference):

例子(参考):

ArrayList aList = new ArrayList();
//Add elements to ArrayList object
aList.add("1");
aList.add("2");
aList.add("3");
aList.add("4");
aList.add("5");
Collections.reverse(aList);
System.out.println("After Reverse Order, ArrayList Contains : " + aList);

#2


18  

Not the simplest way but if you're a fan of recursion you might be interested in the following method to reverse an ArrayList:

这不是最简单的方法,但如果你是递归的爱好者,你可能会对以下方法感兴趣:

public ArrayList<Object> reverse(ArrayList<Object> list) {
    if(list.size() > 1) {                   
        Object value = list.remove(0);
        reverse(list);
        list.add(value);
    }
    return list;
}

Or non-recursively:

或非递归:

public ArrayList<Object> reverse(ArrayList<Object> list) {
    for(int i = 0, j = list.size() - 1; i < j; i++) {
        list.add(i, list.remove(j));
    }
    return list;
}

#3


9  

The trick here is defining "reverse". One can modify the list in place, create a copy in reverse order, or create a view in reversed order.

这里的诀窍是定义“反向”。可以修改列表,以相反的顺序创建副本,或者以相反的顺序创建视图。

The simplest way, intuitively speaking, is Collections.reverse:

直观地说,最简单的方法就是收集。

Collections.reverse(myList);

This method modifies the list in place. That is, Collections.reverse takes the list and overwrites its elements, leaving no unreversed copy behind. This is suitable for some use cases, but not for others; furthermore, it assumes the list is modifiable. If this is acceptable, we're good.

这个方法修改了列表。也就是说,集合。反向获取列表并覆盖其元素,不会留下未反转的副本。这适用于某些用例,但不适用于其他用例;此外,它假定列表是可修改的。如果这是可以接受的,我们很好。


If not, one could create a copy in reverse order:

如果没有,可以按相反顺序创建副本:

static <T> List<T> reverse(final List<T> list) {
    final List<T> result = new ArrayList<>(list);
    Collections.reverse(result);
    return result;
}

This approach works, but requires iterating over the list twice. The copy constructor (new ArrayList<>(list)) iterates over the list, and so does Collections.reverse. We can rewrite this method to iterate only once, if we're so inclined:

这种方法有效,但需要对列表进行两次迭代。复制构造函数(new ArrayList<>(list))遍历列表,并进行排序。我们可以重写这个方法,只迭代一次,如果我们想:

static <T> List<T> reverse(final List<T> list) {
    final int size = list.size();
    final int last = size - 1;

    // create a new list, with exactly enough initial capacity to hold the (reversed) list
    final List<T> result = new ArrayList<>(size);

    // iterate through the list in reverse order and append to the result
    for (int i = last; i >= 0; --i) {
        final T element = list.get(i);
        result.add(element);
    }

    // result now holds a reversed copy of the original list
    return result;
}

This is more efficient, but also more verbose.

这更有效,但也更冗长。

Alternatively, we can rewrite the above to use Java 8's stream API, which some people find more concise and legible than the above:

或者,我们可以重写上面的代码来使用Java 8的流API,有些人认为它比上面的更简洁、更清晰:

static <T> List<T> reverse(final List<T> list) {
    final int last = list.size() - 1;
    return IntStream.rangeClosed(0, last) // a stream of all valid indexes into the list
        .map(i -> (last - i))             // reverse order
        .mapToObj(list::get)              // map each index to a list element
        .collect(Collectors.toList());    // wrap them up in a list
}

nb. that Collectors.toList() makes very few guarantees about the result list. If you want to ensure the result comes back as an ArrayList, use Collectors.toCollection(ArrayList::new) instead.

nb。tolist()对结果列表的保证很少。如果您希望确保结果以ArrayList的形式返回,可以使用Collectors.toCollection(ArrayList::new)。


The third option is to create a view in reversed order. This is a more complicated solution, and worthy of further reading/its own question. Guava's Lists#reverse method is a viable starting point.

第三个选项是按相反的顺序创建视图。这是一个更复杂的解决方案,值得进一步阅读。Guava的清单#反向方法是一个可行的起点。

Choosing a "simplest" implementation is left as an exercise for the reader.

选择“最简单”的实现是留给读者的练习。

#4


5  

Solution without using extra ArrayList or combination of add() and remove() methods. Both can have negative impact if you have to reverse a huge list.

解决方案不使用额外的ArrayList或add()和remove()方法的组合。如果你不得不推翻一个庞大的列表,这两个因素都会产生负面影响。

 public ArrayList<Object> reverse(ArrayList<Object> list) {

    for (int i = 0; i < list.size() / 2; i++) {
        Object temp = list.get(i);
        list.set(i, list.get(list.size() - i - 1));
        list.set(list.size() - i - 1, temp);
 }

#5


2  

ArrayList<Integer> myArray = new ArrayList<Integer>();

myArray.add(1);
myArray.add(2);
myArray.add(3);

int reverseArrayCounter = myArray.size() - 1;

for (int i = reverseArrayCounter; i >= 0; i--) {
    System.out.println(myArray.get(i));
}

#6


0  

A little more readable :)

更容易读懂一点:)

public static <T> ArrayList<T> reverse(ArrayList<T> list) {
    int length = list.size();
    ArrayList<T> result = new ArrayList<T>(length);

    for (int i = length - 1; i >= 0; i--) {
        result.add(list.get(i));
    }

    return result;
}

#7


0  

Another recursive solution

另一个递归解决方案

 public static String reverse(ArrayList<Float> list) {
   if (list.size() == 1) {
       return " " +list.get(0);
   }
   else {
       return " "+ list.remove(list.size() - 1) + reverse(list);
   } 
 }

#8


0  

Just in case we are using Java 8, then we can make use of Stream. The ArrayList is random access list and we can get a stream of elements in reverse order and then collect it into a new ArrayList.

如果我们正在使用Java 8,那么我们可以使用流。ArrayList是随机访问列表,我们可以得到一个反向的元素流,然后将它收集到一个新的ArrayList中。

public static void main(String[] args) {
        ArrayList<String> someDummyList = getDummyList();
        System.out.println(someDummyList);
        int size = someDummyList.size() - 1;
        ArrayList<String> someDummyListRev = IntStream.rangeClosed(0,size).mapToObj(i->someDummyList.get(size-i)).collect(Collectors.toCollection(ArrayList::new));
        System.out.println(someDummyListRev);
    }

    private static ArrayList<String> getDummyList() {
        ArrayList dummyList = new ArrayList();
        //Add elements to ArrayList object
        dummyList.add("A");
        dummyList.add("B");
        dummyList.add("C");
        dummyList.add("D");
        return dummyList;
    }

The above approach is not suitable for LinkedList as that is not random-access. We can also make use of instanceof to check as well.

上述方法不适用于LinkedList,因为它不是随机访问的。我们也可以使用instanceof来检查。

#9


0  

Reversing a ArrayList in a recursive way and without creating a new list for adding elements :

以递归方式反转ArrayList,而不创建添加元素的新list:

   public class ListUtil {

    public static void main(String[] args) {
        ArrayList<String> arrayList = new ArrayList<String>();
        arrayList.add("1");
        arrayList.add("2");
        arrayList.add("3");
        arrayList.add("4");
        arrayList.add("5");
        System.out.println("Reverse Order: " + reverse(arrayList));

    }

    public static <T> List<T> reverse(List<T> arrayList) {
        return reverse(arrayList,0,arrayList.size()-1);
    }
    public static <T> List<T> reverse(List<T> arrayList,int startIndex,int lastIndex) {

        if(startIndex<lastIndex) {
            T t=arrayList.get(lastIndex);
            arrayList.set(lastIndex,arrayList.get(startIndex));
            arrayList.set(startIndex,t);
            startIndex++;
            lastIndex--;
            reverse(arrayList,startIndex,lastIndex);
        }
        return arrayList;
    }

}

#1


666  

Collections.reverse(aList);

Example (Reference):

例子(参考):

ArrayList aList = new ArrayList();
//Add elements to ArrayList object
aList.add("1");
aList.add("2");
aList.add("3");
aList.add("4");
aList.add("5");
Collections.reverse(aList);
System.out.println("After Reverse Order, ArrayList Contains : " + aList);

#2


18  

Not the simplest way but if you're a fan of recursion you might be interested in the following method to reverse an ArrayList:

这不是最简单的方法,但如果你是递归的爱好者,你可能会对以下方法感兴趣:

public ArrayList<Object> reverse(ArrayList<Object> list) {
    if(list.size() > 1) {                   
        Object value = list.remove(0);
        reverse(list);
        list.add(value);
    }
    return list;
}

Or non-recursively:

或非递归:

public ArrayList<Object> reverse(ArrayList<Object> list) {
    for(int i = 0, j = list.size() - 1; i < j; i++) {
        list.add(i, list.remove(j));
    }
    return list;
}

#3


9  

The trick here is defining "reverse". One can modify the list in place, create a copy in reverse order, or create a view in reversed order.

这里的诀窍是定义“反向”。可以修改列表,以相反的顺序创建副本,或者以相反的顺序创建视图。

The simplest way, intuitively speaking, is Collections.reverse:

直观地说,最简单的方法就是收集。

Collections.reverse(myList);

This method modifies the list in place. That is, Collections.reverse takes the list and overwrites its elements, leaving no unreversed copy behind. This is suitable for some use cases, but not for others; furthermore, it assumes the list is modifiable. If this is acceptable, we're good.

这个方法修改了列表。也就是说,集合。反向获取列表并覆盖其元素,不会留下未反转的副本。这适用于某些用例,但不适用于其他用例;此外,它假定列表是可修改的。如果这是可以接受的,我们很好。


If not, one could create a copy in reverse order:

如果没有,可以按相反顺序创建副本:

static <T> List<T> reverse(final List<T> list) {
    final List<T> result = new ArrayList<>(list);
    Collections.reverse(result);
    return result;
}

This approach works, but requires iterating over the list twice. The copy constructor (new ArrayList<>(list)) iterates over the list, and so does Collections.reverse. We can rewrite this method to iterate only once, if we're so inclined:

这种方法有效,但需要对列表进行两次迭代。复制构造函数(new ArrayList<>(list))遍历列表,并进行排序。我们可以重写这个方法,只迭代一次,如果我们想:

static <T> List<T> reverse(final List<T> list) {
    final int size = list.size();
    final int last = size - 1;

    // create a new list, with exactly enough initial capacity to hold the (reversed) list
    final List<T> result = new ArrayList<>(size);

    // iterate through the list in reverse order and append to the result
    for (int i = last; i >= 0; --i) {
        final T element = list.get(i);
        result.add(element);
    }

    // result now holds a reversed copy of the original list
    return result;
}

This is more efficient, but also more verbose.

这更有效,但也更冗长。

Alternatively, we can rewrite the above to use Java 8's stream API, which some people find more concise and legible than the above:

或者,我们可以重写上面的代码来使用Java 8的流API,有些人认为它比上面的更简洁、更清晰:

static <T> List<T> reverse(final List<T> list) {
    final int last = list.size() - 1;
    return IntStream.rangeClosed(0, last) // a stream of all valid indexes into the list
        .map(i -> (last - i))             // reverse order
        .mapToObj(list::get)              // map each index to a list element
        .collect(Collectors.toList());    // wrap them up in a list
}

nb. that Collectors.toList() makes very few guarantees about the result list. If you want to ensure the result comes back as an ArrayList, use Collectors.toCollection(ArrayList::new) instead.

nb。tolist()对结果列表的保证很少。如果您希望确保结果以ArrayList的形式返回,可以使用Collectors.toCollection(ArrayList::new)。


The third option is to create a view in reversed order. This is a more complicated solution, and worthy of further reading/its own question. Guava's Lists#reverse method is a viable starting point.

第三个选项是按相反的顺序创建视图。这是一个更复杂的解决方案,值得进一步阅读。Guava的清单#反向方法是一个可行的起点。

Choosing a "simplest" implementation is left as an exercise for the reader.

选择“最简单”的实现是留给读者的练习。

#4


5  

Solution without using extra ArrayList or combination of add() and remove() methods. Both can have negative impact if you have to reverse a huge list.

解决方案不使用额外的ArrayList或add()和remove()方法的组合。如果你不得不推翻一个庞大的列表,这两个因素都会产生负面影响。

 public ArrayList<Object> reverse(ArrayList<Object> list) {

    for (int i = 0; i < list.size() / 2; i++) {
        Object temp = list.get(i);
        list.set(i, list.get(list.size() - i - 1));
        list.set(list.size() - i - 1, temp);
 }

#5


2  

ArrayList<Integer> myArray = new ArrayList<Integer>();

myArray.add(1);
myArray.add(2);
myArray.add(3);

int reverseArrayCounter = myArray.size() - 1;

for (int i = reverseArrayCounter; i >= 0; i--) {
    System.out.println(myArray.get(i));
}

#6


0  

A little more readable :)

更容易读懂一点:)

public static <T> ArrayList<T> reverse(ArrayList<T> list) {
    int length = list.size();
    ArrayList<T> result = new ArrayList<T>(length);

    for (int i = length - 1; i >= 0; i--) {
        result.add(list.get(i));
    }

    return result;
}

#7


0  

Another recursive solution

另一个递归解决方案

 public static String reverse(ArrayList<Float> list) {
   if (list.size() == 1) {
       return " " +list.get(0);
   }
   else {
       return " "+ list.remove(list.size() - 1) + reverse(list);
   } 
 }

#8


0  

Just in case we are using Java 8, then we can make use of Stream. The ArrayList is random access list and we can get a stream of elements in reverse order and then collect it into a new ArrayList.

如果我们正在使用Java 8,那么我们可以使用流。ArrayList是随机访问列表,我们可以得到一个反向的元素流,然后将它收集到一个新的ArrayList中。

public static void main(String[] args) {
        ArrayList<String> someDummyList = getDummyList();
        System.out.println(someDummyList);
        int size = someDummyList.size() - 1;
        ArrayList<String> someDummyListRev = IntStream.rangeClosed(0,size).mapToObj(i->someDummyList.get(size-i)).collect(Collectors.toCollection(ArrayList::new));
        System.out.println(someDummyListRev);
    }

    private static ArrayList<String> getDummyList() {
        ArrayList dummyList = new ArrayList();
        //Add elements to ArrayList object
        dummyList.add("A");
        dummyList.add("B");
        dummyList.add("C");
        dummyList.add("D");
        return dummyList;
    }

The above approach is not suitable for LinkedList as that is not random-access. We can also make use of instanceof to check as well.

上述方法不适用于LinkedList,因为它不是随机访问的。我们也可以使用instanceof来检查。

#9


0  

Reversing a ArrayList in a recursive way and without creating a new list for adding elements :

以递归方式反转ArrayList,而不创建添加元素的新list:

   public class ListUtil {

    public static void main(String[] args) {
        ArrayList<String> arrayList = new ArrayList<String>();
        arrayList.add("1");
        arrayList.add("2");
        arrayList.add("3");
        arrayList.add("4");
        arrayList.add("5");
        System.out.println("Reverse Order: " + reverse(arrayList));

    }

    public static <T> List<T> reverse(List<T> arrayList) {
        return reverse(arrayList,0,arrayList.size()-1);
    }
    public static <T> List<T> reverse(List<T> arrayList,int startIndex,int lastIndex) {

        if(startIndex<lastIndex) {
            T t=arrayList.get(lastIndex);
            arrayList.set(lastIndex,arrayList.get(startIndex));
            arrayList.set(startIndex,t);
            startIndex++;
            lastIndex--;
            reverse(arrayList,startIndex,lastIndex);
        }
        return arrayList;
    }

}