001/* 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache License, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017package org.apache.commons.lang3; 018 019import java.lang.reflect.Array; 020import java.util.ArrayList; 021import java.util.Collection; 022import java.util.Collections; 023import java.util.List; 024import java.util.Set; 025import java.util.function.BiConsumer; 026import java.util.function.BinaryOperator; 027import java.util.function.Consumer; 028import java.util.function.Function; 029import java.util.function.Predicate; 030import java.util.function.Supplier; 031import java.util.stream.Collector; 032import java.util.stream.Collectors; 033import java.util.stream.Stream; 034 035import org.apache.commons.lang3.Functions.FailableConsumer; 036import org.apache.commons.lang3.Functions.FailableFunction; 037import org.apache.commons.lang3.Functions.FailablePredicate; 038 039/** 040 * Provides utility functions, and classes for working with the 041 * {@code java.util.stream} package, or more generally, with Java 8 lambdas. More 042 * specifically, it attempts to address the fact that lambdas are supposed 043 * not to throw Exceptions, at least not checked Exceptions, AKA instances 044 * of {@link Exception}. This enforces the use of constructs like 045 * <pre> 046 * Consumer<java.lang.reflect.Method> consumer = (m) -> { 047 * try { 048 * m.invoke(o, args); 049 * } catch (Throwable t) { 050 * throw Functions.rethrow(t); 051 * } 052 * }; 053 * stream.forEach(consumer); 054 * </pre> 055 * Using a {@link FailableStream}, this can be rewritten as follows: 056 * <pre> 057 * Streams.failable(stream).forEach((m) -> m.invoke(o, args)); 058 * </pre> 059 * Obviously, the second version is much more concise and the spirit of 060 * Lambda expressions is met better than in the first version. 061 * 062 * @see Stream 063 * @see Functions 064 * @since 3.10 065 * @deprecated Use {@link org.apache.commons.lang3.stream.Streams}. 066 */ 067@Deprecated 068public class Streams { 069 070 /** 071 * A reduced, and simplified version of a {@link Stream} with 072 * failable method signatures. 073 * @param <O> The streams element type. 074 * @deprecated Use {@link org.apache.commons.lang3.stream.Streams.FailableStream}. 075 */ 076 @Deprecated 077 public static class FailableStream<O extends Object> { 078 079 private Stream<O> stream; 080 private boolean terminated; 081 082 /** 083 * Constructs a new instance with the given {@code stream}. 084 * @param stream The stream. 085 */ 086 public FailableStream(final Stream<O> stream) { 087 this.stream = stream; 088 } 089 090 protected void assertNotTerminated() { 091 if (terminated) { 092 throw new IllegalStateException("This stream is already terminated."); 093 } 094 } 095 096 protected void makeTerminated() { 097 assertNotTerminated(); 098 terminated = true; 099 } 100 101 /** 102 * Returns a FailableStream consisting of the elements of this stream that match 103 * the given FailablePredicate. 104 * 105 * <p>This is an intermediate operation. 106 * 107 * @param predicate a non-interfering, stateless predicate to apply to each 108 * element to determine if it should be included. 109 * @return the new stream 110 */ 111 public FailableStream<O> filter(final FailablePredicate<O, ?> predicate){ 112 assertNotTerminated(); 113 stream = stream.filter(Functions.asPredicate(predicate)); 114 return this; 115 } 116 117 /** 118 * Performs an action for each element of this stream. 119 * 120 * <p>This is a terminal operation. 121 * 122 * <p>The behavior of this operation is explicitly nondeterministic. 123 * For parallel stream pipelines, this operation does <em>not</em> 124 * guarantee to respect the encounter order of the stream, as doing so 125 * would sacrifice the benefit of parallelism. For any given element, the 126 * action may be performed at whatever time and in whatever thread the 127 * library chooses. If the action accesses shared state, it is 128 * responsible for providing the required synchronization. 129 * 130 * @param action a non-interfering action to perform on the elements 131 */ 132 public void forEach(final FailableConsumer<O, ?> action) { 133 makeTerminated(); 134 stream().forEach(Functions.asConsumer(action)); 135 } 136 137 /** 138 * Performs a mutable reduction operation on the elements of this stream using a 139 * {@code Collector}. A {@code Collector} 140 * encapsulates the functions used as arguments to 141 * {@link #collect(Supplier, BiConsumer, BiConsumer)}, allowing for reuse of 142 * collection strategies and composition of collect operations such as 143 * multiple-level grouping or partitioning. 144 * 145 * <p>If the underlying stream is parallel, and the {@code Collector} 146 * is concurrent, and either the stream is unordered or the collector is 147 * unordered, then a concurrent reduction will be performed 148 * (see {@link Collector} for details on concurrent reduction.) 149 * 150 * <p>This is a terminal operation. 151 * 152 * <p>When executed in parallel, multiple intermediate results may be 153 * instantiated, populated, and merged so as to maintain isolation of 154 * mutable data structures. Therefore, even when executed in parallel 155 * with non-thread-safe data structures (such as {@code ArrayList}), no 156 * additional synchronization is needed for a parallel reduction. 157 * 158 * Note 159 * The following will accumulate strings into an ArrayList: 160 * <pre>{@code 161 * List<String> asList = stringStream.collect(Collectors.toList()); 162 * }</pre> 163 * 164 * <p>The following will classify {@code Person} objects by city: 165 * <pre>{@code 166 * Map<String, List<Person>> peopleByCity 167 * = personStream.collect(Collectors.groupingBy(Person::getCity)); 168 * }</pre> 169 * 170 * <p>The following will classify {@code Person} objects by state and city, 171 * cascading two {@code Collector}s together: 172 * <pre>{@code 173 * Map<String, Map<String, List<Person>>> peopleByStateAndCity 174 * = personStream.collect(Collectors.groupingBy(Person::getState, 175 * Collectors.groupingBy(Person::getCity))); 176 * }</pre> 177 * 178 * @param <R> the type of the result 179 * @param <A> the intermediate accumulation type of the {@code Collector} 180 * @param collector the {@code Collector} describing the reduction 181 * @return the result of the reduction 182 * @see #collect(Supplier, BiConsumer, BiConsumer) 183 * @see Collectors 184 */ 185 public <A, R> R collect(final Collector<? super O, A, R> collector) { 186 makeTerminated(); 187 return stream().collect(collector); 188 } 189 190 /** 191 * Performs a mutable reduction operation on the elements of this FailableStream. 192 * A mutable reduction is one in which the reduced value is a mutable result 193 * container, such as an {@code ArrayList}, and elements are incorporated by updating 194 * the state of the result rather than by replacing the result. This produces a result equivalent to: 195 * <pre>{@code 196 * R result = supplier.get(); 197 * for (T element : this stream) 198 * accumulator.accept(result, element); 199 * return result; 200 * }</pre> 201 * 202 * <p>Like {@link #reduce(Object, BinaryOperator)}, {@code collect} operations 203 * can be parallelized without requiring additional synchronization. 204 * 205 * <p>This is a terminal operation. 206 * 207 * Note There are many existing classes in the JDK whose signatures are 208 * well-suited for use with method references as arguments to {@code collect()}. 209 * For example, the following will accumulate strings into an {@code ArrayList}: 210 * <pre>{@code 211 * List<String> asList = stringStream.collect(ArrayList::new, ArrayList::add, 212 * ArrayList::addAll); 213 * }</pre> 214 * 215 * <p>The following will take a stream of strings and concatenates them into a 216 * single string: 217 * <pre>{@code 218 * String concat = stringStream.collect(StringBuilder::new, StringBuilder::append, 219 * StringBuilder::append) 220 * .toString(); 221 * }</pre> 222 * 223 * @param <R> type of the result 224 * @param <A> Type of the accumulator. 225 * @param pupplier a function that creates a new result container. For a 226 * parallel execution, this function may be called 227 * multiple times and must return a fresh value each time. 228 * @param accumulator An associative, non-interfering, stateless function for 229 * incorporating an additional element into a result 230 * @param combiner An associative, non-interfering, stateless 231 * function for combining two values, which must be compatible with the 232 * accumulator function 233 * @return The result of the reduction 234 */ 235 public <A, R> R collect(final Supplier<R> pupplier, final BiConsumer<R, ? super O> accumulator, final BiConsumer<R, R> combiner) { 236 makeTerminated(); 237 return stream().collect(pupplier, accumulator, combiner); 238 } 239 240 /** 241 * Performs a reduction on the elements of this stream, using the provided 242 * identity value and an associative accumulation function, and returns 243 * the reduced value. This is equivalent to: 244 * <pre>{@code 245 * T result = identity; 246 * for (T element : this stream) 247 * result = accumulator.apply(result, element) 248 * return result; 249 * }</pre> 250 * 251 * but is not constrained to execute sequentially. 252 * 253 * <p>The {@code identity} value must be an identity for the accumulator 254 * function. This means that for all {@code t}, 255 * {@code accumulator.apply(identity, t)} is equal to {@code t}. 256 * The {@code accumulator} function must be an associative function. 257 * 258 * <p>This is a terminal operation. 259 * 260 * Note Sum, min, max, average, and string concatenation are all special 261 * cases of reduction. Summing a stream of numbers can be expressed as: 262 * 263 * <pre>{@code 264 * Integer sum = integers.reduce(0, (a, b) -> a+b); 265 * }</pre> 266 * 267 * or: 268 * 269 * <pre>{@code 270 * Integer sum = integers.reduce(0, Integer::sum); 271 * }</pre> 272 * 273 * <p>While this may seem a more roundabout way to perform an aggregation 274 * compared to simply mutating a running total in a loop, reduction 275 * operations parallelize more gracefully, without needing additional 276 * synchronization and with greatly reduced risk of data races. 277 * 278 * @param identity the identity value for the accumulating function 279 * @param accumulator an associative, non-interfering, stateless 280 * function for combining two values 281 * @return the result of the reduction 282 */ 283 public O reduce(final O identity, final BinaryOperator<O> accumulator) { 284 makeTerminated(); 285 return stream().reduce(identity, accumulator); 286 } 287 288 /** 289 * Returns a stream consisting of the results of applying the given 290 * function to the elements of this stream. 291 * 292 * <p>This is an intermediate operation. 293 * 294 * @param <R> The element type of the new stream 295 * @param mapper A non-interfering, stateless function to apply to each element 296 * @return the new stream 297 */ 298 public <R> FailableStream<R> map(final FailableFunction<O, R, ?> mapper) { 299 assertNotTerminated(); 300 return new FailableStream<>(stream.map(Functions.asFunction(mapper))); 301 } 302 303 /** 304 * Converts the FailableStream into an equivalent stream. 305 * @return A stream, which will return the same elements, which this FailableStream would return. 306 */ 307 public Stream<O> stream() { 308 return stream; 309 } 310 311 /** 312 * Returns whether all elements of this stream match the provided predicate. 313 * May not evaluate the predicate on all elements if not necessary for 314 * determining the result. If the stream is empty then {@code true} is 315 * returned and the predicate is not evaluated. 316 * 317 * <p>This is a short-circuiting terminal operation. 318 * 319 * Note 320 * This method evaluates the <em>universal quantification</em> of the 321 * predicate over the elements of the stream (for all x P(x)). If the 322 * stream is empty, the quantification is said to be <em>vacuously 323 * satisfied</em> and is always {@code true} (regardless of P(x)). 324 * 325 * @param predicate A non-interfering, stateless predicate to apply to 326 * elements of this stream 327 * @return {@code true} If either all elements of the stream match the 328 * provided predicate or the stream is empty, otherwise {@code false}. 329 */ 330 public boolean allMatch(final FailablePredicate<O, ?> predicate) { 331 assertNotTerminated(); 332 return stream().allMatch(Functions.asPredicate(predicate)); 333 } 334 335 /** 336 * Returns whether any elements of this stream match the provided 337 * predicate. May not evaluate the predicate on all elements if not 338 * necessary for determining the result. If the stream is empty then 339 * {@code false} is returned and the predicate is not evaluated. 340 * 341 * <p>This is a short-circuiting terminal operation. 342 * 343 * Note 344 * This method evaluates the <em>existential quantification</em> of the 345 * predicate over the elements of the stream (for some x P(x)). 346 * 347 * @param predicate A non-interfering, stateless predicate to apply to 348 * elements of this stream 349 * @return {@code true} if any elements of the stream match the provided 350 * predicate, otherwise {@code false} 351 */ 352 public boolean anyMatch(final FailablePredicate<O, ?> predicate) { 353 assertNotTerminated(); 354 return stream().anyMatch(Functions.asPredicate(predicate)); 355 } 356 } 357 358 /** 359 * Converts the given {@link Stream stream} into a {@link FailableStream}. 360 * This is basically a simplified, reduced version of the {@link Stream} 361 * class, with the same underlying element stream, except that failable 362 * objects, like {@link FailablePredicate}, {@link FailableFunction}, or 363 * {@link FailableConsumer} may be applied, instead of 364 * {@link Predicate}, {@link Function}, or {@link Consumer}. The idea is 365 * to rewrite a code snippet like this: 366 * <pre> 367 * final List<O> list; 368 * final Method m; 369 * final Function<O,String> mapper = (o) -> { 370 * try { 371 * return (String) m.invoke(o); 372 * } catch (Throwable t) { 373 * throw Functions.rethrow(t); 374 * } 375 * }; 376 * final List<String> strList = list.stream() 377 * .map(mapper).collect(Collectors.toList()); 378 * </pre> 379 * as follows: 380 * <pre> 381 * final List<O> list; 382 * final Method m; 383 * final List<String> strList = Functions.stream(list.stream()) 384 * .map((o) -> (String) m.invoke(o)).collect(Collectors.toList()); 385 * </pre> 386 * While the second version may not be <em>quite</em> as 387 * efficient (because it depends on the creation of additional, 388 * intermediate objects, of type FailableStream), it is much more 389 * concise, and readable, and meets the spirit of Lambdas better 390 * than the first version. 391 * @param <O> The streams element type. 392 * @param stream The stream, which is being converted. 393 * @return The {@link FailableStream}, which has been created by 394 * converting the stream. 395 */ 396 public static <O> FailableStream<O> stream(final Stream<O> stream) { 397 return new FailableStream<>(stream); 398 } 399 400 /** 401 * Converts the given {@link Collection} into a {@link FailableStream}. 402 * This is basically a simplified, reduced version of the {@link Stream} 403 * class, with the same underlying element stream, except that failable 404 * objects, like {@link FailablePredicate}, {@link FailableFunction}, or 405 * {@link FailableConsumer} may be applied, instead of 406 * {@link Predicate}, {@link Function}, or {@link Consumer}. The idea is 407 * to rewrite a code snippet like this: 408 * <pre> 409 * final List<O> list; 410 * final Method m; 411 * final Function<O,String> mapper = (o) -> { 412 * try { 413 * return (String) m.invoke(o); 414 * } catch (Throwable t) { 415 * throw Functions.rethrow(t); 416 * } 417 * }; 418 * final List<String> strList = list.stream() 419 * .map(mapper).collect(Collectors.toList()); 420 * </pre> 421 * as follows: 422 * <pre> 423 * final List<O> list; 424 * final Method m; 425 * final List<String> strList = Functions.stream(list.stream()) 426 * .map((o) -> (String) m.invoke(o)).collect(Collectors.toList()); 427 * </pre> 428 * While the second version may not be <em>quite</em> as 429 * efficient (because it depends on the creation of additional, 430 * intermediate objects, of type FailableStream), it is much more 431 * concise, and readable, and meets the spirit of Lambdas better 432 * than the first version. 433 * @param <O> The streams element type. 434 * @param stream The stream, which is being converted. 435 * @return The {@link FailableStream}, which has been created by 436 * converting the stream. 437 */ 438 public static <O> FailableStream<O> stream(final Collection<O> stream) { 439 return stream(stream.stream()); 440 } 441 442 /** 443 * @deprecated Use {@link org.apache.commons.lang3.stream.Streams.ArrayCollector}. 444 */ 445 @Deprecated 446 public static class ArrayCollector<O> implements Collector<O, List<O>, O[]> { 447 private static final Set<Characteristics> characteristics = Collections.emptySet(); 448 private final Class<O> elementType; 449 450 public ArrayCollector(final Class<O> elementType) { 451 this.elementType = elementType; 452 } 453 454 @Override 455 public Supplier<List<O>> supplier() { 456 return ArrayList::new; 457 } 458 459 @Override 460 public BiConsumer<List<O>, O> accumulator() { 461 return List::add; 462 } 463 464 @Override 465 public BinaryOperator<List<O>> combiner() { 466 return (left, right) -> { 467 left.addAll(right); 468 return left; 469 }; 470 } 471 472 @Override 473 public Function<List<O>, O[]> finisher() { 474 return list -> { 475 @SuppressWarnings("unchecked") 476 final O[] array = (O[]) Array.newInstance(elementType, list.size()); 477 return list.toArray(array); 478 }; 479 } 480 481 @Override 482 public Set<Characteristics> characteristics() { 483 return characteristics; 484 } 485 } 486 487 /** 488 * Returns a {@code Collector} that accumulates the input elements into a 489 * new array. 490 * 491 * @param pElementType Type of an element in the array. 492 * @param <O> the type of the input elements 493 * @return a {@code Collector} which collects all the input elements into an 494 * array, in encounter order 495 */ 496 public static <O extends Object> Collector<O, ?, O[]> toArray(final Class<O> pElementType) { 497 return new ArrayCollector<>(pElementType); 498 } 499}