![](/img/trans.png)
[英]Java: How to remove elements from a list while iterating over/adding to it
[英]Remove space from a list object while iterating using Java 8
這是我的代碼,它返回空格和一些有效字符串。 但是,我的要求是使空間無效並僅收集字符串
List<String> stateCodes = stateList.stream()
.map(state-> physician.getStateDetails().getStateCode())
.collect(Collectors.toList());
當我打印 stateCodes 時,它返回
[ , , 197, 148, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ]
這里我只需要 [197,148]
過濾掉空值。 我不確定您的輸出中是否為空String
。 如果是,您可以使用以下方法過濾掉它們:
List<String> stateCodes =
stateList.stream()
.map(state-> physician.getStateDetails().getStateCode())
.filter(s -> !s.isEmpty())
.collect(Collectors.toList());
注意:您可以添加trim()
(到map
或filter
步驟)來過濾掉只包含空格的String
:
List<String> stateCodes =
stateList.stream()
.map(state-> physician.getStateDetails().getStateCode().trim())
.filter(s -> !s.isEmpty())
.collect(Collectors.toList());
我會做:
List<String> stateCodes =
stateList.stream()
.map(state-> physician.getStateDetails().getStateCode())
.filter(s -> !s.trim().isEmpty())
.collect(Collectors.toList());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.