Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Java 8 streams process in pairs

Just kicking the tires of Java 8, and noticed Lamdas and streams functional programing.

Was wondering if a simple command line args consumer could use streams.

Cant figure out howto get at two stream elements at once however... Plus below I'd need to handle args that do and dont take values, so couldnt do any odd/even trickery. Would have consider args to always start with a dash, and optional values never do.

String[] args = ("-v", "-c", "myconfigfile", "-o", "outputfile");

Arrays.toList(args).stream().map( a,v -> evalArg(a,v));

public static void evalArg(String arg, String val) {
    switch(arg) {
        case "-v":
            verbose = true;
            break;
        case "-c":
            config_file = val;
            break;
        case "-o":
            output_file = val;
            break;
        default:
            System.err.println("unknown argument " + arg + " " + val);
            break;
    }
}
like image 692
Alan Jurgensen Avatar asked Aug 01 '26 13:08

Alan Jurgensen


1 Answers

If you have key-value pairs then you can use following:

public static void main(final String[] args) {
    String[] args = {"-v", "value", "-c", "myconfigfile", "-o", "outputfile"};

    pairStream(Arrays.asList(args), (param, value) -> param + ": " + value)
        .forEach(System.out::println);
}

public static <X, Y> Stream<Y> pairStream(List<X> list, BiFunction<X, X, Y> mapper) {
    Supplier<X> s = list.iterator()::next;
    return Stream.generate(() -> mapper.apply(s.get(), s.get()))
        .limit(list.size() / 2);
}

// Result:
//    -v: value
//    -c: myconfigfile
//    -o: outputfile
like image 145
Alex Avatar answered Aug 04 '26 04:08

Alex



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!