简体   繁体   中英

How can I avoid using streams and if else statements?

I'm coding the functionality for the drill-down page for my Spring Web page.

It all works but I want to simplify it so it's not as long. What could I do differently?

Ideally, I'd like NOT to use streams.

List<Long> longNumbers = List.of(s.split(", ")).stream().map(num -> Long.parseLong(num)).collect(toList());
        long nr = longNumbers.get(0);

        long nr2 = 0;
            if (longNumbers.size() < 2) {
                nr2 = longNumbers.get(0);
            }

            else {
                nr2 = longNumbers.get(1);
            }

        long nr3 = 0;
            if (longNumbers.size() < 3) {
                nr3 = longNumbers.get(0);
            }
        
            else {
                nr3 = longNumbers.get(2);
            }

No streams, no if solution - use java.util.Scanner . Main idea:

var scanner = new Scanner(s).useDelimiter(", ");
var nr = scanner.nextLong();
var nr2 = scanner.hasNextLong() ? scanner.nextLong() : nr;
var nr3 = scanner.hasNextLong() ? scanner.nextLong() : nr;

just no if solution, streams bit changed (no List used)

long[] longNumbers = Pattern.compile(", ")
                     .splitAsStream(s)
                     .mapToLong(Long::parseLong)
                     .toArray();
long nr = longNumbers[0];
long nr2 = longNumbers.length < 2 ? nr : longNumbers[1];
long nr3 = longNumbers.length < 3 ? nr : longNumbers[2];

First option, to get rid of the stream: use any kind of loop Second option, if you know that s is no longer than 3 values, you can use a regex with capturing groups. But that will be at least twice as hard to understand.

Personally I would keep the stream (once you are used to it, it's often much better readable than loops), but remove the repetitive ifs.

Add a getOrDefault method

private Long getOrDefault(List<Long> longNumbers, int index) {
   if (longNumbers.size() < index+1) return longNumbers.get(0)
   else return longNumber.get(index)
}

And then, instead of repeating the if everywhere you just do

List<Long>.... your stream stuff
nr = longNumber.get(0);
nr2=getOrDefault(longNumbers, 1);
nr3=getOrDefault(longNumbers, 2);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM