How to get a reversed list view on a list in Java?

前端 未结 12 788
自闭症患者
自闭症患者 2020-11-28 21:05

I want to have a reversed list view on a list (in a similar way than List#sublist provides a sublist view on a list). Is there some function which provides this

12条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-28 21:31

    I know this is an old post but today I was looking for something like this. In the end I wrote the code myself:

    private List reverseList(List myList) {
        List invertedList = new ArrayList();
        for (int i = myList.size() - 1; i >= 0; i--) {
            invertedList.add(myList.get(i));
        }
        return invertedList;
    }
    

    Not recommended for long Lists, this is not optimized at all. It's kind of an easy solution for controlled scenarios (the Lists I handle have no more than 100 elements).

    Hope it helps somebody.

提交回复
热议问题