admin管理员组文章数量:1430948
I have the following Java method to get the last price of my List of object.
So I need to change it to return Message at the user and 0.0 as value if the method does not return value. This is the current method:
public static Double getUltimoPrezzo(List<ArticoliPerFornitore> lista){
try{
//ArticoliPerFornitore lastContact = Collections.max(lista, Comparator.nullsLast(Comparatorparing(c -> c.getDataUltimoAcquisto())));
//return lastContact.getPrezzoUltimoAcquisto();
ArticoliPerFornitore lastContact = lista.stream()
.filter(c -> c.getDataUltimoAcquisto() != null)
.collect(Collectors.maxBy(Comparator
paring(c -> c.getDataUltimoAcquisto())))
.orElseThrow(()->
new IllegalArgumentException("List is empty")
);
return lastContact.getPrezzoUltimoAcquisto();
}catch(Exception e){
log.logStackTrace(e);
}
return null;
}
I need to change the code in "orElseThrow()" with this code:
VisualMessage.getPrezzoVenditaNullo(nomeArticolo);
return 0.0;
I have the following Java method to get the last price of my List of object.
So I need to change it to return Message at the user and 0.0 as value if the method does not return value. This is the current method:
public static Double getUltimoPrezzo(List<ArticoliPerFornitore> lista){
try{
//ArticoliPerFornitore lastContact = Collections.max(lista, Comparator.nullsLast(Comparatorparing(c -> c.getDataUltimoAcquisto())));
//return lastContact.getPrezzoUltimoAcquisto();
ArticoliPerFornitore lastContact = lista.stream()
.filter(c -> c.getDataUltimoAcquisto() != null)
.collect(Collectors.maxBy(Comparator
paring(c -> c.getDataUltimoAcquisto())))
.orElseThrow(()->
new IllegalArgumentException("List is empty")
);
return lastContact.getPrezzoUltimoAcquisto();
}catch(Exception e){
log.logStackTrace(e);
}
return null;
}
I need to change the code in "orElseThrow()" with this code:
VisualMessage.getPrezzoVenditaNullo(nomeArticolo);
return 0.0;
Share
Improve this question
asked Nov 19, 2024 at 9:12
bircastribircastri
2,16714 gold badges55 silver badges132 bronze badges
6
|
Show 1 more comment
3 Answers
Reset to default 2That's not going to work. orElseThrow ALWAYS throws an Exception, NEVER returns a value. The name of the method should tell you that instantly.
There are alternative methods you can use instead to return something rather than throw an exception.You'll likely want to use orElse or orElseGet instead, or a completely different mechanism altogether.
Returning 0.0 for an empty result is IMO dangerous btw, as the result of the actual operation may also be 0.0 if there is data in the collection (but depending on your business logic that may be desirable, check carefully).
To return the prezzoUltimoAcquisto
of the last contact if one is found and 0.0 otherwise, get an Optional
out of your stream operation and use its map
and orElse
methods.
public static Double getUltimoPrezzo(List<ArticoliPerFornitore> lista){
try {
Optional<ArticoliPerFornitore> lastContact = lista.stream()
.filter(c -> c.getDataUltimoAcquisto() != null)
.collect(Collectors.maxBy(Comparator
paring(c -> c.getDataUltimoAcquisto())));
// if only needed to send message to user,
// replace by just the return statement if no message needed
if (lastContact.isEmpty()) {
/* Message to user */
return 0.0; // or null?
} else {
return lastContact.map(lc -> lc.getPrezzoUltimoAcquisto())
.orElse(0.0);
}
} catch (Exception e) {
log.logStackTrace(e);
}
return null; // was that intentional?
}
not tested, missing some details
Note that returning 0.0 can be confusing if it is a valid value, callers of the method would not be able to know if nothing was found or it comes from an item (articoli)! (see jwenting's answer
One option would be to return null
as you already are doing in case of an Exception. By the way, most often it is not a good idea to catch Exception
, better be more specific! Catch for example RuntimeException
.
Another option, my favorite so far, is to return the OptionalDouble
that you can get from lastContact.mapToDouble(lc -> lc.getPrezzoUltimoAcquisto())
and throw the Exception instead of catching it (leave out try
-catch
). Let the caller decide how to handle these, including any message to the user - I do not like the idea of a getter writing messages to the user - it can be logged in the getter, but it should not know if the user is using a console or a GUI.
A third option is to return Double.NaN
.
You can replace orElseThrow () with orElseGet () to call your VisualMessage method and return 0. 0 if no value is found.
本文标签: javaReturn 0 value in orElseThrowStack Overflow
版权声明:本文标题:java - Return 0 value in orElseThrow - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745570618a2664024.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
orElseThrow
is for throwing an exception which is very different from returning a value. It sounds like you just want.orElse(0.0)
? – Jon Skeet Commented Nov 19, 2024 at 9:16.orElseGet
if you need to do more than just supply a value. – greg-449 Commented Nov 19, 2024 at 9:230.0
isn't a statement on its own, is it? If you want to return it, then do so:.orElseGet(()-> { VisualMessage.getPrezzoVenditaNullo(nomeArticolo); return 0.0; })
– Jon Skeet Commented Nov 19, 2024 at 10:10.collect(Collectors.maxBy(…))
you can simply writemax(…)
– Holger Commented Nov 19, 2024 at 11:57