Java의 각 루프마다 역순으로 할 수 있습니까?
Java를 사용하여 List를 역순으로 실행해야합니다.
그래서 이것이 전달되는 곳 :
for(String string: stringList){
//...do something
}
각 구문 에 대해 를 사용하여 stringList를 역순으로 반복하는 방법이 있습니까?
명확성을 위해 : 목록을 역순으로 반복하는 방법을 알고 있지만 (호기심을 위해) 각 스타일 에 대해 목록을 수행하는 방법을 알고 싶습니다 .
Collections.reverse 메소드는 실제로 원래 목록의 요소가 역순으로 복사 된 새 목록을 리턴하므로 원래 목록의 크기와 관련하여 O (n) 성능을 갖습니다.
보다 효율적인 솔루션으로 목록의 반전 된보기를 반복 가능으로 표시하는 데코레이터를 작성할 수 있습니다. 데코레이터가 반환 한 반복자는 데코 레이팅 된 목록의 ListIterator를 사용하여 요소를 역순으로 살펴 봅니다.
예를 들면 다음과 같습니다.
public class Reversed<T> implements Iterable<T> {
private final List<T> original;
public Reversed(List<T> original) {
this.original = original;
}
public Iterator<T> iterator() {
final ListIterator<T> i = original.listIterator(original.size());
return new Iterator<T>() {
public boolean hasNext() { return i.hasPrevious(); }
public T next() { return i.previous(); }
public void remove() { i.remove(); }
};
}
public static <T> Reversed<T> reversed(List<T> original) {
return new Reversed<T>(original);
}
}
그리고 당신은 그것을 다음과 같이 사용할 것입니다 :
import static Reversed.reversed;
...
List<String> someStrings = getSomeStrings();
for (String s : reversed(someStrings)) {
doSomethingWith(s);
}
목록을 보려면 Google Guava Library를 사용할 수 있습니다 .
for (String item : Lists.reverse(stringList))
{
// ...
}
참고 하지 않는 전체 수집을 반대하거나 같은 것을 할 수는 - 그냥 역순으로, 반복 및 랜덤 액세스 할 수 있습니다. 이것은 컬렉션을 먼저 되 돌리는 것보다 효율적입니다.Lists.reverse
임의의 이터 러블을 뒤집으려면, 모든 것을 읽고 나서 거꾸로 "재생"해야합니다.
(당신이 이미 그것을 사용하지 않는 경우, 나는 것 철저하게 당신이 한 번 봐 가지고 추천 구아바를 . 그것은 좋은 물건입니다.)
목록 (집합과 달리)은 순서가 지정된 모음이며이 목록을 반복하면 계약에 따라 주문이 유지됩니다. 스택이 역순으로 반복 될 것으로 예상했지만 불행히도 그렇지 않습니다. 그래서 내가 생각할 수있는 가장 간단한 해결책은 다음과 같습니다.
for (int i = stack.size() - 1; i >= 0; i--) {
System.out.println(stack.get(i));
}
이것이 "각"루프 솔루션이 아니라는 것을 알고 있습니다. Google 컬렉션과 같은 새로운 라이브러리를 도입하는 것보다 for 루프를 사용하고 싶습니다.
Collections.reverse ()도 작업을 수행하지만 복사본을 역순으로 반환하는 대신 목록을 업데이트합니다.
This will mess with the original list and also needs to be called outside of the loop. Also you don't want to perform a reverse every time you loop - would that be true if one of the Iterables.reverse ideas
was applied?
Collections.reverse(stringList);
for(String string: stringList){
//...do something
}
AFAIK there isn't a standard "reverse_iterator" sort of thing in the standard library that supports the for-each syntax which is already a syntactic sugar they brought late into the language.
You could do something like for(Item element: myList.clone().reverse()) and pay the associated price.
This also seems fairly consistent with the apparent phenomenon of not giving you convenient ways to do expensive operations - since a list, by definition, could have O(N) random access complexity (you could implement the interface with a single-link), reverse iteration could end up being O(N^2). Of course, if you have an ArrayList, you don't pay that price.
This may be an option. Hope there is a better way to start from last element than to while loop to the end.
public static void main(String[] args) {
List<String> a = new ArrayList<String>();
a.add("1");a.add("2");a.add("3");a.add("4");a.add("5");
ListIterator<String> aIter=a.listIterator();
while(aIter.hasNext()) aIter.next();
for (;aIter.hasPrevious();)
{
String aVal = aIter.previous();
System.out.println(aVal);
}
}
As of the comment: You should be able to use Apache Commons ReverseListIterator
Iterable<String> reverse
= new IteratorIterable(new ReverseListIterator(stringList));
for(String string: reverse ){
//...do something
}
As @rogerdpack said, you need to wrap the ReverseListIterator
as an Iterable
.
Not without writing some custom code which will give you an enumerator which will reverse the elements for you.
You should be able to do it in Java by creating a custom implementation of Iterable which will return the elements in reverse order.
Then, you would instantiate the wrapper (or call the method, what-have-you) which would return the Iterable implementation which reverses the element in the for each loop.
You can use the Collections class http://java.sun.com/j2se/1.4.2/docs/api/java/util/Collections.html to reverse the list then loop.
You'd need to reverse your collection if you want to use the for each syntax out of the box and go in reverse order.
All answers above only fulfill the requirement, either by wrapping another method or calling some foreign code outside;
Here is the solution copied from the Thinking in Java 4th edition, chapter 11.13.1 AdapterMethodIdiom;
Here is the code:
// The "Adapter Method" idiom allows you to use foreach
// with additional kinds of Iterables.
package holding;
import java.util.*;
@SuppressWarnings("serial")
class ReversibleArrayList<T> extends ArrayList<T> {
public ReversibleArrayList(Collection<T> c) { super(c); }
public Iterable<T> reversed() {
return new Iterable<T>() {
public Iterator<T> iterator() {
return new Iterator<T>() {
int current = size() - 1; //why this.size() or super.size() wrong?
public boolean hasNext() { return current > -1; }
public T next() { return get(current--); }
public void remove() { // Not implemented
throw new UnsupportedOperationException();
}
};
}
};
}
}
public class AdapterMethodIdiom {
public static void main(String[] args) {
ReversibleArrayList<String> ral =
new ReversibleArrayList<String>(
Arrays.asList("To be or not to be".split(" ")));
// Grabs the ordinary iterator via iterator():
for(String s : ral)
System.out.print(s + " ");
System.out.println();
// Hand it the Iterable of your choice
for(String s : ral.reversed())
System.out.print(s + " ");
}
} /* Output:
To be or not to be
be to not or be To
*///:~
Definitely a late answer to this question. One possibility is to use the ListIterator in a for loop. It's not as clean as colon-syntax, but it works.
List<String> exampleList = new ArrayList<>();
exampleList.add("One");
exampleList.add("Two");
exampleList.add("Three");
//Forward iteration
for (String currentString : exampleList) {
System.out.println(currentString);
}
//Reverse iteration
for (ListIterator<String> itr = exampleList.listIterator(exampleList.size()); itr.hasPrevious(); /*no-op*/ ) {
String currentString = itr.previous();
System.out.println(currentString);
}
Credit for the ListIterator syntax goes to "Ways to iterate over a list in Java"
A work Around :
Collections.reverse(stringList).forEach(str -> ...);
Or with guava :
Lists.reverse(stringList).forEach(str -> ...);
참고URL : https://stackoverflow.com/questions/1098117/can-one-do-a-for-each-loop-in-java-in-reverse-order
'Programing' 카테고리의 다른 글
리눅스에서 bash로 어제 날짜 가져 오기, DST 안전 (0) | 2020.06.20 |
---|---|
값으로 객체를 제거하는 배열 확장 (0) | 2020.06.20 |
최대 높이를 설정 해제하는 방법? (0) | 2020.06.19 |
파이썬의 유휴 창을 지우는 방법은 무엇입니까? (0) | 2020.06.19 |
콘솔 제작자에서 리더를 사용할 수 없음 (0) | 2020.06.19 |