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 myObjects = getObjects();
numRecords = saveToDb(myObjects); // numRecords=3
List 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?
解决方案
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);