is some elegant way to find and modify some specific object in java? I have method like that:
public update(MyObj o) {
for (MyObj objToModify: DATA) {
if (objToModify.getId() == o.getId()) {
objToModify.setName(o.getName());
// and so on ...
}
}
}
Is possible to rewrite to lambda for example, or some other feature of Java 8? I had a lot of properties so I will prefer some option where I couldn't write manually set up all of new properties.
You can do it in the following way, this will go over the whole stream and update elements even if there is more then one matching:
DATA.stream().filter(a -> a.getId() == o.getId()).forEach(a -> a.setName(o.getName()));
Or if you are sure that you only need to update one element:
DATA.stream().filter(a -> a.getId() == o.getId()).
findAny().ifPresent(a -> a.setName(o.getName()));
Both solutions will throw NullPointerException if DATA has null elements the same as your original solution, if it's a posiibility and you want to prevent it you need to also check that a is not null in filter.
You can use lambda expression to do what you are trying to do
public update(MyObj o) {
DATA.forEach(objToModify -> {
if (objToModify.getId() == o.getId()) {
objToModify.setName(o.getName());
// and so on ...
}
});
}
although i am not sure if using lambda expression in your case will be more efficient than using for-each loop.
Related
retList.sort((comp1, comp2) ->
compartmentOrderMap.get(comp2.getCompartment()).compareTo(compartmentOrderMap
.get(comp1.getCompartment())));
I want to add a null check before comparing. How can I do that?
retList.sort((comp1, comp2) ->
if(compartmentOrderMap.get(comp2.getCompartment()) != null && compartmentOrderMap.get(comp1.getCompartment()) != null)
compartmentOrderMap.get(comp2.getCompartment()).compareTo(compartmentOrderMap
.get(comp1.getCompartment()));
);
//I want to do something like this
Your operation
retList.sort((comp1, comp2) ->
compartmentOrderMap.get(comp2.getCompartment())
.compareTo(compartmentOrderMap.get(comp1.getCompartment())));
is equivalent to
retList.sort(Comparator.comparing(
c -> compartmentOrderMap.get(c.getCompartment()),
Comparator.reverseOrder()));
With this factory based form, you can easily replace the value comparator with a null safe variant, e.g.
retList.sort(Comparator.comparing(
c -> compartmentOrderMap.get(c.getCompartment()),
Comparator.nullsFirst(Comparator.reverseOrder())));
You have to decide for a policy. Instead of nullsFirst you can also use nullsLast.
you have to put {} inside the lambda for multiple line code:
retList.sort((comp1, comp2) -> {
if(compartmentOrderMap.get(comp2.getCompartment()) != null && compartmentOrderMap.get(comp1.getCompartment()) != null)
return compartmentOrderMap.get(comp2.getCompartment()).compareTo(compartmentOrderMap
.get(comp1.getCompartment()));
else
// throw a RuntimeException or return some integer value based on your logic
});
Use if/then/else to specify your needs. If you want all of this within one line, check the ternary operator on
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html
It is explained including some examples here:
https://www.tutorialspoint.com/Java-Ternary-Operator-Examples
I have following method which is used for creating a order in the database, order has many items and, item has many bills. iPadPOSOrderDTO is the order which is going to base saved into the database.
so, the loop based code for creating order is the following
private void createNewOrder(IPadPOSOrderDTO iPadPOSOrderDTO) {
IPadPOSOrderV2 order = mapper.map(iPadPOSOrderDTO, IPadPOSOrderV2.class);
if(order.getOrderV2Bills()!=null && order.getOrderV2Bills().size()>0){
for(IPadPOSOrderV2Bill orderBill : order.getOrderV2Bills()){
orderBill.setOrder(order);
if(orderBill.getiPadPOSOrderV2BillItems()!=null && orderBill.getiPadPOSOrderV2BillItems().size()>0){
for(IPadPOSOrderV2BillItems orderBillItem : orderBill.getiPadPOSOrderV2BillItems()){
orderBillItem.setiPadPOSOrderV2Bill(orderBill);
orderBillItem.setOrderId(order.getOrderId());
}
}
}
}
sessionFactory.
getCurrentSession().save(order);
}
I wanted to refactor above code to use Java 8 streams API.
So, I did the following
private void createNewOrderV2(IPadPOSOrderDTO iPadPOSOrderDTO) {
IPadPOSOrderV2 order = mapper.map(iPadPOSOrderDTO, IPadPOSOrderV2.class);
if(order.getOrderV2Bills()!=null && order.getOrderV2Bills().size()>0){
order.getOrderV2Bills().stream().forEach(e -> { createBill(order,e);});
}
sessionFactory.
getCurrentSession().save(order);
}
private void createBill(IPadPOSOrderV2 ipadExistingOrderFromDatabase, IPadPOSOrderV2Bill iPadPOSOrderV2Bill) {
iPadPOSOrderV2Bill.setOrder(ipadExistingOrderFromDatabase);
if(iPadPOSOrderV2Bill.getiPadPOSOrderV2BillItems()!=null && iPadPOSOrderV2Bill.getiPadPOSOrderV2BillItems().size()>0){
iPadPOSOrderV2Bill.getiPadPOSOrderV2BillItems().stream().forEach(e -> createBillItem(ipadExistingOrderFromDatabase,iPadPOSOrderV2Bill,e));
}
}
private void createBillItem(IPadPOSOrderV2 ipadExistingOrderFromDatabase, IPadPOSOrderV2Bill iPadPOSOrderV2Bill, IPadPOSOrderV2BillItems iPadPOSOrderV2BillItem) {
iPadPOSOrderV2BillItem.setiPadPOSOrderV2Bill(iPadPOSOrderV2Bill);
iPadPOSOrderV2BillItem.setOrderId(ipadExistingOrderFromDatabase.getOrderId());
ipadExistingOrderFromDatabase.getOrderV2Bills().stream().forEach(e -> { createBill(ipadExistingOrderFromDatabase,e);});
}
could somebody share their experience and advice me if I am making the correct use of streams API for this refactoring.
Note that those size checks aren't really necessary. An empty list would result in an empty stream and thus nothing would get applied. The only benefit would be that you'd be able to avoid having to create the stream altogether but I highly doubt the performance difference would even be noticeble.
If you want to convert a potentially null collection to a stream you might want to use a small helper function:
public <T> Stream<T> collectionToStream(Collection<T> collection) {
return Optional.ofNullable(collection).map(Collection::stream).orElseGet(Stream::empty);
}
Using forEach() you could then do something like this:
private void createNewOrder(IPadPOSOrderDTO iPadPOSOrderDTO) {
IPadPOSOrderV2 order = mapper.map(iPadPOSOrderDTO, IPadPOSOrderV2.class);
collectionToStream(order.getOrderV2Bills()).forEach( orderBill -> {
orderBill.setOrder(order);
collectionToStream(orderBill.getiPadPOSOrderV2BillItems()).forEach(orderBillItem -> {
orderBillItem.setiPadPOSOrderV2Bill(orderBill);
orderBillItem.setOrderId(order.getOrderId());
}
}
}
}
sessionFactory.getCurrentSession().save(order);
}
Note that this isn't that different from your initial code and thus you should think about whether that conversion would make sense.
Converting your nested loops to a fully sequential stream would be harder and in the end not that different because you can't just flat map orderBill to a stream of orderBillItem. Doing that would not make orderBill available downstream so you'd have to call orderBillItem.setiPadPOSOrderV2Bill(orderBill); before returning the nested stream. That would end up in code very similar to the above and add no benefit because you're not using the returned stream.
Filter out the nulls ommiting the null checks
private void createNewOrderV2(IPadPOSOrderDTO iPadPOSOrderDTO) {
IPadPOSOrderV2 order = mapper.map(iPadPOSOrderDTO, IPadPOSOrderV2.class);
order.getOrderV2Bills().stream().filter(Objects::nonNull).forEach(e -> createBill(order, e));
sessionFactory.getCurrentSession().save(order);
}
private void createBill(IPadPOSOrderV2 ipadExistingOrderFromDatabase, IPadPOSOrderV2Bill iPadPOSOrderV2Bill) {
iPadPOSOrderV2Bill.setOrder(ipadExistingOrderFromDatabase);
iPadPOSOrderV2Bill.getiPadPOSOrderV2BillItems().stream().filter(Objects::nonNull).forEach(e -> {
e.setiPadPOSOrderV2Bill(iPadPOSOrderV2Bill);
e.setOrderId(ipadExistingOrderFromDatabase.getOrderId());
});
}
By the way your createBill() is called by the createBillItem and also the other way around, is this correct?
I have a POJO:
class MyObject {
private Double a;
private String b;
//constructor, getter + setter
}
Some function is creating a list of this POJO. Some values for a might be null, so I want to replace them with 0.0. At the moment I am doing it like this.
public List<MyObject> fetchMyObjects(Predicate predicate) {
List<MyObject> list = getMyListsOfTheDatabase(predicate);
list
.forEach(myObject -> {
if (myObject.getA() == null) {
myObject.setA(0.0);
}
});
return list;
}
Is there a way to integrate the forEach in the return? Something like
return list
.stream()
.someStatement();
It's not about, if this is the best place to convert the nulls to zero, but rather a questions to better understand the streaming api.
Use the peek function
Returns a stream consisting of the elements of this stream, additionally performing the provided action on each element as elements are consumed from the resulting stream.
public List<MyObject> fetchMyObjects(Predicate predicate) {
return getMyListsOfTheDatabase(predicate)
.stream()
.peek(it -> if(it.getA() == null) it.setA(0.0))
.collect(Collectors.toList());
}
While others have been happy to answer your question as it stands, allow me to step a step back and give you the answer you didn’t ask for (but maybe the answer that you want): You don’t want to do that. A stream operation should be free from side effects. What you are asking for is exactly a stream operation that has the side effect of modifying the original objects going into the stream. Such is poor code style and likely to confuse those reading your code after you.
The code you already have solves your problem much more nicely than any combined stream pipeline.
What you may want to have if you can modify your POJO is either a constructor that sets a to 0 if null was retrieved from the database, or method that does it that you may call from list.forEach:
list.forEach(MyObject::setAToZeroIfNull);
It's not about, if this is the best place to convert the nulls to
zero, but rather a questions to better understand the streaming api.
That’s fair. In any case I will let this answer stand for anyone else popping by.
You can't return the same List instance with a single statement, but you can return a new List instance containing the same (possibly modified) elements:
return list.stream()
.map(myObject -> {
if (myObject.getA() == null) {
myObject.setA(0.0);
}
return myObject;
})
.collect(Collectors.toList());
Actually you should be using List::replaceAll:
list.replaceAll(x -> {
if(x.getA() == null) x.setA(0.0D);
return x;
})
forEach doesn't have a return value, so what you might be looking for is map
return list
.stream()
.map(e -> {
if (e.getA() == null) e.setA(0d);
return e;
})
.whateverElse()...
The following would be fine:
list.stream()
.filter(obj -> obj.getA() == null)
.forEach(obj -> obj.setA(0.0));
return list;
However in your case just returning a Stream might be more appropriate (depends):
public Stream<MyObject> fetchMyObjects(Predicate predicate) {
return getMyListsOfTheDatabase(predicate);
}
public Stream<MyObject> streamMyObjects(List<MyObject> list) {
return list.stream()
.peek(obj -> {
if (obj.getA() == null) {
obj.setA(0.0);
}
});
}
I personally never used peek, but here it corrects values.
On code conventions, which are more string in the java community:
Indentation: Java took 4 as opposed to C++'s 3 as more separate methods,
and less indentation was expected. Debatable but okay.
For generic type parameters often a single capital like T, C, S.
For lambda parameters short names, often a single letter, hence I used obj.
One area that I often finding confusing with java 8 streams is when an intermediate result can be empty, and you need to take alternate paths if it's empty or not empty.
For instance, if I have code like this:
String pymtRef = defaultValue;
Optional<PaymentTender> paymentTender = paymentTenders.stream()
.filter(pt -> (pt.getFlag() == Flag.N || pt.getFlag() == null)).findFirst();
if (paymentTender.isPresent()) {
pymtRef = paymentTender.get().getId();
}
return pymtRef;
I would like to figure out how to remove the conditional block and do this in a single stream.
If I simply call ".map" on the filter result, that can work if it found a matching entry. If not, I get a NoSuchElementException.
I might instead use "ifPresent()", but the return type of that is "void".
Is there any way to make this cleaner?
Update:
The solution using "orElse()" works fine.
The entire method now looks something like this:
public String getPaymentReference(OrderContext orderContext) {
List<PaymentTender> paymentTenders = getPaymentTenders(orderContext);
if (paymentTenders.size() == 1) {
return paymentTenders.get(0).getId();
}
return paymentTenders.stream()
.filter(pt -> (pt.getAutoBill() == AutoBill.N || pt.getAutoBill() == null))
.findFirst().map(pt -> pt.getId()).orElse(DEFAULT_VALUE);
}
Can you think of a way to include the first conditional in the stream without making it more complex?
Calling get() straight after map will yield an exception if the Optional has an empty state, instead call orElse after map and provide a default value:
paymentTenders.stream()
.filter(pt -> (pt.getFlag() == Flag.N || pt.getFlag() == null))
.findFirst()
.map(PaymentTender::getId)
.orElse(someDefaultValue);
Edit:
As for:
Can you think of a way to include the first conditional in the stream
without making it more complex?
No, this is better the way you've done it. it's more readable and easier to follow.
introducing any type of logic to make it into one pipeline (if possible) will just end of being complex and hence harder to follow and understand.
You can do it in one statement via
public String getPaymentReference(OrderContext orderContext) {
List<PaymentTender> paymentTenders = getPaymentTenders(orderContext);
return paymentTenders.stream()
.filter(paymentTenders.size() == 1? pt -> true:
pt -> pt.getAutoBill() == AutoBill.N || pt.getAutoBill() == null)
.findFirst().map(PaymentTender::getId).orElse(DEFAULT_VALUE);
}
Note that this will not repeat the evaluation of the paymentTenders.size() == 1 for every element, but use a different function, depending on the state. When the condition is fulfilled, pt -> true will accept any element, which will result in the sole element being accepted as intended. Otherwise, the ordinary predicate, pt -> pt.getAutoBill() == AutoBill.N || pt.getAutoBill() == null is used.
I was refactoring some old code of mine that I've written and I stumbeled on this code:
List<OcmImageData> fullImagePool = new ArrayList<>();
if (CollectionUtils.isNotEmpty(style.getTestMH())) {
fullImagePool.addAll(style.getTestMH());
}
if (CollectionUtils.isNotEmpty(style.getTrousers())) {
fullImagePool.addAll(style.getTrousers());
}
if (CollectionUtils.isNotEmpty(style.getDetailRevers())) {
fullImagePool.addAll(style.getDetailRevers());
}
if (CollectionUtils.isNotEmpty(style.getDetailCuffs())) {
fullImagePool.addAll(style.getDetailCuffs());
}
if (CollectionUtils.isNotEmpty(style.getDetailInner())) {
fullImagePool.addAll(style.getDetailInner());
}
if (CollectionUtils.isNotEmpty(style.getDetailMaterial())) {
fullImagePool.addAll(style.getDetailMaterial());
}
if (CollectionUtils.isNotEmpty(style.getComposing())) {
fullImagePool.addAll(style.getComposing());
}
...
So basically I need to create an ArrayList which contains all Lists here referenced, because those can be null (they are fetched out of the database from an closed sourced framework, and unfortunately its null if he doesn't find anything), I need to check everytime if the collection is not null to add them into this pool which looks just weird.
Is there a library or Collection-Framework utility class that gives me the posibility to add a collection to another without performing the null-safe check?
In Java 8 Use below code:-
Optional.ofNullable(listToBeAdded).ifPresent(listToBeAddedTo::addAll)
listToBeAdded - The list whose elements are to be added.
listToBeAddedTo - The list to which you are adding elements using addAll.
Just write a small utility method:
public static <E> void addAllIfNotNull(List<E> list, Collection<? extends E> c) {
if (c != null) {
list.addAll(c);
}
}
so that you can write:
List<OcmImageData> fullImagePool = new ArrayList<>();
addAllIfNotNull(fullImagePool, style.getTestMH());
addAllIfNotNull(fullImagePool, style.getTrousers());
addAllIfNotNull(fullImagePool, style.getDetailRevers());
// ...etc
Using Java 8:
List<OcmImageData> fullImagePool = Stream.of(style.getTestMH(), /* etc */)
.filter(Objects::nonNull)
.flatMap(l -> l.stream())
.collect(Collectors.toList());
This refactors cleanly to
for (OcmImageData elem : new List<OcmImageData>[] { style.getTestMH(), style.getTrousers() /* etc */}) {
if (CollectionUtils.isNotEmpty(elem)) {
fullImagePull.addAll(elem);
}
}
To answer your original question, no, you will have to do your own null check. You can see Guava's methods will throw an NPE, and Apache's methods explicitly require the input to be not null.