Say I have three objects that I save to the database and set the db generated ID into. I don't know the order of the objects returned from the method saveToDb
. But I want to junit test that those generated IDs are there. How do I do that within in stream? I want to do something like this:
List<MyObject> myObjects = getObjects();
numRecords = saveToDb(myObjects); // numRecords=3
List<Integer> intArray = Arrays.asList(1, 2, 3);
intArray.stream()
.forEach(it -> myObjects.stream()
.filter(it2 -> it2.getId().equals(it))
.????
But I'm not sure where my assertEquals()
would go in a statement like this. Or is my approach all wrong? I know I could use a simple for-loop, but I like the elegance of streams. Additionally, is there a way to dynamically create the intArray, in case I have more than 3 myObjects?
Introduced in Java 8, the Stream API is used to process collections of objects. A stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result. A stream is not a data structure instead it takes input from the Collections, Arrays or I/O channels.
Java 8 offers the possibility to create streams out of three primitive types: int, long and double. As Stream<T> is a generic interface, and there is no way to use primitives as a type parameter with generics, three new special interfaces were created: IntStream, LongStream, DoubleStream.
Yes, streams are sometimes slower than loops, but they can also be equally fast; it depends on the circumstances. The point to take home is that sequential streams are no faster than loops.
It seems (if i understood correctly), how about something like this:
boolean result = Arrays.asList(1, 2, 3).stream()
.allMatch(i -> objects
.stream()
.map(MyObject::getId)
.filter(j -> j == i).findAny().isPresent());
Assert.assertTrue(result);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With