删除' null'来自Java的LinkedListMultimap
我有以下代码,在打印或保存文件中时,我想删除“ null”值。
有时我不必将任何值传递给变量。因此,在这种情况下,我需要打印的钥匙,但没有任何“ null”。我该怎么做?
我必须使用linkedlistmultimap
,因为我可能具有重复的键,并且要保留进入地图的顺序。
public static void main(String[] args) {
Multimap<String, String> data = LinkedListMultimap.create();
data.put("NAME", getName());
data.put("AGE", getAge());
data.put("DEPARTMENT", getDepartment());
data.forEach((key, value) -> System.out.println("[" + key + "]" + " " + value));
}
当前输出:
[NAME] Joe
[AGE] 25
[DEPARTMENT] null
预期输出:
[NAME] Joe
[AGE] 25
[DEPARTMENT]
I have the below code, and I want to remove the 'null' values when printing or saving in a file.
There are times I don't have to pass any values to a variable. So, in those cases, I need the keys printed, but without any 'null'. How can I do that?
I have to use LinkedListMultimap
as I may have duplicate keys and want to keep the order of entry to the map.
public static void main(String[] args) {
Multimap<String, String> data = LinkedListMultimap.create();
data.put("NAME", getName());
data.put("AGE", getAge());
data.put("DEPARTMENT", getDepartment());
data.forEach((key, value) -> System.out.println("[" + key + "]" + " " + value));
}
Current output:
[NAME] Joe
[AGE] 25
[DEPARTMENT] null
Expected output:
[NAME] Joe
[AGE] 25
[DEPARTMENT]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用 ternary operator :
You can use a ternary operator:
中打印或保存
null
时,删除null
值是没有意义的(null
null < /code> - 表示没有数据,它不能提供任何有用的信息),它是 antpattern 。要从地图中删除
null
值 - 使用remove> remove()
对值集合进行大量删除。除了获得标准地图以获取价值集合外,您还可以使用
values()
方法。如文档中指定的,它在地图的值而不是独立集合的值上返回a view 。并且所有对其进行的更改都将反映在地图中。这就是可以做到的。
Storing and retaining
null
in the collection doesn't make any sense (null
- represents the absence of data, it can't give any useful information), it's an antipattern.To remove
null
values from the map - perform a bulk removal on a collection of values usingremoveIf()
.As well as with standard map to obtain a collection of values, you can use
values()
method. As specified in the documentation, it returns a view over the values of the map and not an independent collection. And all the changes done to it, will be reflected in the map.That's how it can be done.
上面的代码中缺少某些内容。实际上应该是这样:
Something is missing in the code above. Actually it should be like this: