我有以下代码:
private static <T> Map<String, ?> getDifference(final T a, final T b, final Map<String, Function<T, Object>> fields) {
return fields.entrySet().stream()
.map(e -> {
final String name = e.getKey();
final Function<T, Object> getter = e.getValue();
final Object pairKey = getter.apply(a);
final Object pairValue = getter.apply(b);
if (Objects.equals(pairKey, pairValue)) {
return null;
} else {
return Pair.of(name, pairValue);
}
})
.filter(Objects::nonNull)
.collect(Collectors.toMap(Pair::getKey, Pair::getValue));
}
现在,pairValue 可以为空。为了避免描述的 NPE here ,在“收集”时,我希望确保只发送那些非空值。如果为空,我想发送“”。
所以,我试着用这个替换最后一行:
.collect(Collectors.toMap(Pair::getKey,Optional.ofNullable(Pair::getValue).orElse(""));
及其其他修改:
.collect(Collectors.toMap(pair -> pair.getKey(), Optional.ofNullable(pair -> pair.getValue()).orElse(""));
不编译。我不确定这里需要什么。有帮助吗?
最佳答案
您可以只收集到一个 HashMap 中,它允许 null 值而不需要 Optional:
private static <T> Map<String, Object> getDifference(
final T a, final T b, final Map<String, Function<T, Object>> fields) {
return fields.entrySet().stream()
.map(e -> {
final Function<T, Object> getter = e.getValue();
final Object value = getter.apply(b);
return Objects.equals(getter.apply(a),value)? null: Pair.of(e.getKey(), value);
})
.filter(Objects::nonNull)
.collect(HashMap::new, (m,p) -> m.put(p.getKey(),p.getValue()), Map::putAll);
}
顺便说一句,不鼓励在返回类型中使用通配符,它们会使调用者的生活不必要地变得困难,而且没有任何好处。
为了比较,这里没有 Stream 的相同操作:
private static <T> Map<String, Object> getDifference(
final T a, final T b, final Map<String, Function<T, Object>> fields) {
HashMap<String, Object> result = new HashMap<>();
fields.forEach((key, getter) -> {
final Object value = getter.apply(b);
if(!Objects.equals(getter.apply(a), value)) result.put(key, value);
});
return result;
}
当然,这也适用于可选的:
private static <T> Map<String, Optional<Object>> getDifference(
final T a, final T b, final Map<String, Function<T, Object>> fields) {
HashMap<String, Optional<Object>> result = new HashMap<>();
fields.forEach((key, getter) -> {
final Object value = getter.apply(b);
if(!Objects.equals(getter.apply(a), value))
result.put(key, Optional.ofNullable(value));
});
return result;
}
但是如果您只想用空字符串替换 null,则不需要 Optional:
private static <T> Map<String, Object> getDifference(
final T a, final T b, final Map<String, Function<T, Object>> fields) {
HashMap<String, Object> result = new HashMap<>();
fields.forEach((key,getter) -> {
final Object value = getter.apply(b);
if(!Objects.equals(getter.apply(a), value))
result.put(key, value==null? "": value);
});
return result;
}
好吧,如果您只是在 map 函数中而不是在收集器中执行此替换,那么此替换也可以立即使用您的原始代码:
private static <T> Map<String, ?> getDifference(final T a, final T b, final Map<String, Function<T, Object>> fields) {
return fields.entrySet().stream()
.map(e -> {
final String name = e.getKey();
final Function<T, Object> getter = e.getValue();
final Object pairKey = getter.apply(a);
final Object pairValue = getter.apply(b);
if (Objects.equals(pairKey, pairValue)) {
return null;
} else {
return Pair.of(name, pairValue==null? "": pairValue);
}
})
.filter(Objects::nonNull)
.collect(Collectors.toMap(Pair::getKey, Pair::getValue));
}
或
private static <T> Map<String, Object> getDifference(
final T a, final T b, final Map<String, Function<T, Object>> fields) {
return fields.entrySet().stream()
.map(e -> {
final Function<T, Object> getter = e.getValue();
final Object pairValue = getter.apply(b);
return Objects.equals(getter.apply(a), pairValue)? null:
Pair.of(e.getKey(), pairValue==null? "": pairValue);
})
.filter(Objects::nonNull)
.collect(Collectors.toMap(Pair::getKey, Pair::getValue));
}
关于java - 收集可能为空的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48799769/
我试图获取一个长度在1到10之间的字符串,并输出将字符串分解为大小为1、2或3的连续子字符串的所有可能方式。例如:输入:123456将整数分割成单个字符,然后继续查找组合。该代码将返回以下所有数组。[1,2,3,4,5,6][12,3,4,5,6][1,23,4,5,6][1,2,34,5,6][1,2,3,45,6][1,2,3,4,56][12,34,5,6][12,3,45,6][12,3,4,56][1,23,45,6][1,2,34,56][1,23,4,56][12,34,56][123,4,5,6][1,234,5,6][1,2,345,6][1,2,3,456][123
我希望我的UserPrice模型的属性在它们为空或不验证数值时默认为0。这些属性是tax_rate、shipping_cost和price。classCreateUserPrices8,:scale=>2t.decimal:tax_rate,:precision=>8,:scale=>2t.decimal:shipping_cost,:precision=>8,:scale=>2endendend起初,我将所有3列的:default=>0放在表格中,但我不想要这样,因为它已经填充了字段,我想使用占位符。这是我的UserPrice模型:classUserPrice回答before_val
我真的很习惯使用Ruby编写以下代码:my_hash={}my_hash['test']=1Java中对应的数据结构是什么? 最佳答案 HashMapmap=newHashMap();map.put("test",1);我假设? 关于java-等价于Java中的RubyHash,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/22737685/
我有一个这样的哈希数组:[{:foo=>2,:date=>Sat,01Sep2014},{:foo2=>2,:date=>Sat,02Sep2014},{:foo3=>3,:date=>Sat,01Sep2014},{:foo4=>4,:date=>Sat,03Sep2014},{:foo5=>5,:date=>Sat,02Sep2014}]如果:date相同,我想合并哈希值。我对上面数组的期望是:[{:foo=>2,:foo3=>3,:date=>Sat,01Sep2014},{:foo2=>2,:foo5=>5:date=>Sat,02Sep2014},{:foo4=>4,:dat
我有一个包含多个键的散列和一个字符串,该字符串不包含散列中的任何键或包含一个键。h={"k1"=>"v1","k2"=>"v2","k3"=>"v3"}s="thisisanexamplestringthatmightoccurwithakeysomewhereinthestringk1(withspecialcharacterslike(^&*$#@!^&&*))"检查s是否包含h中的任何键的最佳方法是什么,如果包含,则返回它包含的键的值?例如,对于上面的h和s的例子,输出应该是v1。编辑:只有字符串是用户定义的。哈希将始终相同。 最佳答案
我想获取模块中定义的所有常量的值:moduleLettersA='apple'.freezeB='boy'.freezeendconstants给了我常量的名字:Letters.constants(false)#=>[:A,:B]如何获取它们的值的数组,即["apple","boy"]? 最佳答案 为了做到这一点,请使用mapLetters.constants(false).map&Letters.method(:const_get)这将返回["a","b"]第二种方式:Letters.constants(false).map{|c
我正在尝试使用boilerpipe来自JRuby。我看过guide从JRuby调用Java,并成功地将它与另一个Java包一起使用,但无法弄清楚为什么同样的东西不能用于boilerpipe。我正在尝试基本上从JRuby中执行与此Java等效的操作:URLurl=newURL("http://www.example.com/some-location/index.html");Stringtext=ArticleExtractor.INSTANCE.getText(url);在JRuby中试过这个:require'java'url=java.net.URL.new("http://www
我只想对我一直在思考的这个问题有其他意见,例如我有classuser_controller和classuserclassUserattr_accessor:name,:usernameendclassUserController//dosomethingaboutanythingaboutusersend问题是我的User类中是否应该有逻辑user=User.newuser.do_something(user1)oritshouldbeuser_controller=UserController.newuser_controller.do_something(user1,user2)我
什么是ruby的rack或python的Java的wsgi?还有一个路由库。 最佳答案 来自Python标准PEP333:Bycontrast,althoughJavahasjustasmanywebapplicationframeworksavailable,Java's"servlet"APImakesitpossibleforapplicationswrittenwithanyJavawebapplicationframeworktoruninanywebserverthatsupportstheservletAPI.ht
这篇文章是继上一篇文章“Observability:从零开始创建Java微服务并监控它(一)”的续篇。在上一篇文章中,我们讲述了如何创建一个Javaweb应用,并使用Filebeat来收集应用所生成的日志。在今天的文章中,我来详述如何收集应用的指标,使用APM来监控应用并监督web服务的在线情况。源码可以在地址 https://github.com/liu-xiao-guo/java_observability 进行下载。摄入指标指标被视为可以随时更改的时间点值。当前请求的数量可以改变任何毫秒。你可能有1000个请求的峰值,然后一切都回到一个请求。这也意味着这些指标可能不准确,你还想提取最小/