Skip to content

Commit c3c909c

Browse files
committed
GROOVY-11650: Create drain extension method for Queues
1 parent 6cf95da commit c3c909c

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

src/main/java/org/codehaus/groovy/runtime/DefaultGroovyMethods.java

+25
Original file line numberDiff line numberDiff line change
@@ -4094,6 +4094,31 @@ public static void downto(BigDecimal self, Number to, @ClosureParams(FirstParam.
40944094
") to downto() cannot be greater than the value (" + self + ") it's called on."); }
40954095
}
40964096

4097+
//--------------------------------------------------------------------------
4098+
// drain
4099+
4100+
/**
4101+
* Drain the queue of elements, returning them as a list.
4102+
* <pre class="groovyTestCase">
4103+
* def letters = new PriorityQueue(String.CASE_INSENSITIVE_ORDER)
4104+
* letters.addAll(['Z', 'y', 'X', 'a', 'B', 'c'])
4105+
* assert letters.toList() == ['a', 'B', 'c', 'Z', 'X', 'y']
4106+
* assert letters.drain() == ['a', 'B', 'c', 'X', 'y', 'Z']
4107+
* assert letters.empty
4108+
* </pre>
4109+
*
4110+
* @param self a Queue
4111+
* @return a List of elements removed from the head of the queue
4112+
* @since 5.0.0
4113+
*/
4114+
public static <T> List<T> drain(Queue<T> self) {
4115+
List<T> answer = new ArrayList<>();
4116+
while (!self.isEmpty()) {
4117+
answer.add(self.poll());
4118+
}
4119+
return answer;
4120+
}
4121+
40974122
//--------------------------------------------------------------------------
40984123
// drop
40994124

0 commit comments

Comments
 (0)