最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

java - Return 0 value in orElseThrow - Stack Overflow

programmeradmin0浏览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;

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
  • 6 Surely 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
  • Or use .orElseGet if you need to do more than just supply a value. – greg-449 Commented Nov 19, 2024 at 9:23
  • I writed this code: .orElseGet(()-> VisualMessage.getPrezzoVenditaNullo(nomeArticolo); 0.0 ); but is not correct – bircastri Commented Nov 19, 2024 at 9:37
  • 5 Well 0.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
  • 3 Side note: instead of .collect(Collectors.maxBy(…)) you can simply write max(…) – Holger Commented Nov 19, 2024 at 11:57
 |  Show 1 more comment

3 Answers 3

Reset to default 2

That'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.

发布评论

评论列表(0)

  1. 暂无评论