我想转换 public class HttpClientHandlerInterceptor : HttpClientHandler
{
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
if (request.Content is FormUrlEncodedContent)
{
var x = ((FormUrlEncodedContent) request.Content).ReadAsStringAsync().Result;
var contenttype = request.Content.Headers.ContentType.MediaType;
x = x.Replace("client_secret=will+be+ignored&", "");
request.Content = new StringContent(x, Encoding.UTF8, contenttype);
}
return base.SendAsync(request, cancellationToken);
}
}
。
我曾经以非流方式做到如下
ImmutableListMultimap<String, Character> to Map<String, List<Character>>
我想知道如何使用java8 stream way(Collectors.toMap)编写上述相同的逻辑。
请分享您的想法
答案 0 :(得分:4)
您已经可以使用asMap
来简化此操作:
Builder<String, Character> builder = ImmutableListMultimap.builder();
builder.put("12", 'c');
builder.put("12", 'c');
ImmutableListMultimap<String, Character> map = builder.build();
Map<String, List<Character>> map2 = map.asMap()
.entrySet()
.stream()
.collect(Collectors.toMap(Entry::getKey, e -> new ArrayList<>(e.getValue())));
另一方面,如果您使用asMap
的返回类型,则可以使用简单的方法调用:
ImmutableMap<String, Collection<Character>> asMap = map.asMap();
答案 1 :(得分:1)
Map<String, List<Character>> result = reverseImmutableMultiMap.entries().stream()
.collect(groupingBy(Entry::getKey, TreeMap::new, mapping(Entry::getValue, toList())));
重要的细节是mapping。它会转换收集器(toList
),以便它收集List<Character>
而不是List<Entry<String, Character>>
。根据映射函数Entry::getValue
groupingBy会按String
键
toList将使用相同的键收集列表中的所有值
此外,将TreeMap::new
作为参数传递给groupingBy
将确保您获得此特定类型的Map
而不是默认HashMap