Closing over immutable variable and accumulate values across multiple iterations as a lambda expression - Java 8

前端 未结 2 2061
长情又很酷
长情又很酷 2021-01-24 09:56

WebTarget in Jersey client is implemented as a immutable object, and any operations to change the state returns a new WebTarget. To add query params to it, which is coming in as

2条回答
  •  悲哀的现实
    2021-01-24 10:37

    If you want functional approach you need foldLeft(right) or reduce.

    foldLeft is implemented in some libraries, for example Functionaljava and streamEx.

    Functionaljava:

     B foldLeft(final F> bff, final B z)
    
    WebTarget wt = wtCollection.foldLeft(x -> (y -> x.queryParam(...)), new WebTarget());
    

    StreamEx:

     U foldLeft(U seed, BiFunction accumulator) 
    

    UPD stream-reduce

    queryMap.entrySet().stream()
        .reduce(new WebTarget(), (x, y) -> { 
            x.queryParam(y.getKey(), y.getValue()); 
        });
    

提交回复
热议问题