Reputation: 2773
In Java 8, you can write code like the following:
List<Integer> list = IntStream
.range(0, 100)
.boxed()
.collect(Collectors.toCollection(ArrayList::new));
How can I create a custom XStream
class? For example, say I have a class that naturally can be ordered, and you can naturally have predecessors and successors to an object. Like:
public class PurchaseOrder {
public long orderNumber;
public PurchaseOrder(){
orderNumber = 0L;
}
}
Then, I could have a theoretical PurchaseOrderStream that you can write the following code for:
List<PurchaseOrder> list = PurchaseOrderStream
.range(0, 100)
.collect(Collectors.toCollection(ArrayList::new));
How could I go about doing this? Are there any classes or interfaces I need PurchaseOrderStream
to extend
/ implement
? I'm not looking for full source code (though that would be nice), but just a push in the right direction.
Upvotes: 3
Views: 376
Reputation: 37645
The easiest way would just be to use the methods already available. I can't see any reason to reinvent the wheel here.
For example, if you wrote a static method PurchaseOrder getFromId(long id)
you could just do
LongStream.range(0, 100).mapToObj(PurchaseOrder::getFromId)
.collect(Collectors.toCollection(ArrayList::new));
If this isn't short enough, you could write a method
public static Stream<PurchaseOrder> range(long low, long high) {
return LongStream.range(low, high).mapToObj(PurchaseOrder::getFromId);
}
Then you could write
PurchaseOrder.range(0, 100).collect(Collectors.toCollection(ArrayList::new));
Upvotes: 7