String去除list<String>中的空数据
时间: 2023-11-18 14:13:56 浏览: 42
可以使用Java 8的流式操作和过滤器来实现这个功能。代码示例如下:
```java
List<String> list = Arrays.asList("hello", "", "world", "", "java");
List<String> filteredList = list.stream()
.filter(str -> !str.isEmpty())
.collect(Collectors.toList());
System.out.println(filteredList);
```
输出结果为:`[hello, world, java]`
这里使用了`filter`方法来过滤掉空字符串,然后使用`collect`方法将过滤后的结果收集到一个新的列表中。
相关问题
string转list<map>>
要将一个字符串转换为列表<字典>,首先,我们需要使用适当的分隔符将字符串分割成子字符串。然后,我们需要将每个子字符串解析为字典,并添加到列表中。
下面是一个实现的示例代码:
```python
# 定义字符串
string = "{'name': 'Alice', 'age': 25}, {'name': 'Bob', 'age': 30}, {'name': 'Cathy', 'age': 28}"
# 使用逗号分割字符串
substrings = string.split(', ')
# 创建空的列表
map_list = []
# 遍历子字符串并将其解析为字典,然后添加到列表中
for sub in substrings:
# 去除大括号
sub = sub.replace('{', '').replace('}', '')
# 分割键值对
items = sub.split(', ')
# 创建一个空字典
d = {}
# 遍历键值对并添加到字典中
for item in items:
key, value = item.split(': ')
d[key.strip()] = value.strip()
# 将字典添加到列表中
map_list.append(d)
# 打印转换后的列表<字典>
print(map_list)
```
在这个例子中,我们首先将字符串使用逗号分隔符分割成子字符串,然后遍历每个子字符串,并将其解析为字典。最后,将每个字典添加到列表中,并打印出转换后的列表<字典>。
Map<String, List<CoreSpaceExcelBo>> map 根据 CoreSpaceExcelBo对象的CartonCode字段去重,累加CoreSpaceExcelBo中的num字段
首先,需要使用Java的Stream API对List进行处理,将其中的重复元素去掉,并累加重复元素的num字段。可以使用groupingBy方法根据CartonCode字段进行分组,然后使用mapping方法将每个组中的CoreSpaceExcelBo对象转换为其num字段的值,最后使用summingInt方法对这些值进行求和。代码如下:
```
Map<String, List<CoreSpaceExcelBo>> map = new HashMap<>();
map = map.entrySet().stream()
.collect(Collectors.toMap(Map.Entry::getKey,
entry -> entry.getValue().stream().collect(
Collectors.groupingBy(CoreSpaceExcelBo::getCartonCode,
Collectors.mapping(CoreSpaceExcelBo::getNum, Collectors.summingInt(Integer::intValue))))
.entrySet().stream()
.map(e -> new CoreSpaceExcelBo(e.getKey(), e.getValue()))
.collect(Collectors.toList())));
```
这段代码将原始的Map对象中的每个List对象进行处理,将其中的元素根据CartonCode字段进行分组,并且统计每个组中CoreSpaceExcelBo对象的num字段的总和。然后,将这些统计结果封装成新的CoreSpaceExcelBo对象,并存储在新的List中。最后,将这个新的List作为Map中每个键所对应的值。