使用收集器加入char分隔符

时间:2018-05-07 20:28:31

标签: java lambda java-stream collectors

我正在构建一个名为" id"的查询参数,它是一个列表,所以我有类似localhost:8080 / application?id = 1& id = 2& id = 3& ; id = 4

(我知道我的方法不够,我需要写第一个?id =

方法

public Map<Long, String> getSkus(List<ItemPedido> itensPedido) {
    Map<Long, String> skus = new HashMap<>();
    String ids = itensPedido.stream()
            .filter(i -> i.getProduto() != null)
            .map(i -> i.getProduto().getId())
            .collect(Collectors.joining("&id="));
    //TODO 
    return skus;
}

我的问题是:为什么我在 Collectors.joining(&#34;&amp; id =&#34;)中收到此错误?

no suitable method found for collect(java.util.stream.Collector<java.lang.CharSequence,capture#1 of ?,java.lang.String>)
[ERROR]     method java.util.stream.Stream.<R>collect(java.util.function.Supplier<R>,java.util.function.BiConsumer<R,? super java.lang.Long>,java.util.function.BiConsumer<R,R>) is not applicable
[ERROR]       (cannot infer type-variable(s) R
[ERROR]         (actual and formal argument lists differ in length))
[ERROR]     method java.util.stream.Stream.<R,A>collect(java.util.stream.Collector<? super java.lang.Long,A,R>) is not applicable
[ERROR]       (cannot infer type-variable(s) R,A
[ERROR]         (argument mismatch; java.util.stream.Collector<java.lang.CharSequence,capture#1 of ?,java.lang.String> cannot be converted to java.util.stream.Collector<? super java.lang.Long,A,R>))

我正在使用OpenJDK

$ java -version
openjdk version "1.8.0_151"
OpenJDK Runtime Environment (build 1.8.0_151-b12)
OpenJDK 64-Bit Server VM (build 25.151-b12, mixed mode)

1 个答案:

答案 0 :(得分:1)

将您的信息流映射到字符串流:

.map(i -> i.getProduto().getId().toString())