仅显示 List<Map<String, List<String>>> 中的映射键
Display only map key from List<Map<String, List<String>>>
我有以下结构:
List<Map<String, List<String>>> filters
考虑以下示例:
filters=[{product=[A1, A2, A3]}]
我只想显示地图键而不是值。
预期输出:
product
我尝试了以下方法:
String op = filters.get(i).keySet().toString();
这给了我以下输出:
[product]
我也尝试过使用 .stream(),但没有用。我只想显示键(一个或多个),即在这种情况下:product
如有任何帮助,我们将不胜感激。
这应该可以解决问题
List<String> collect = filters.stream()
.flatMap(entry ->
entry.keySet().stream())
.collect(Collectors.toList());
collect 将拥有地图的所有键。
您可以使用:
filters.stream().flatMap(c -> c.keySet().stream())
.forEach(System.out::println);
编辑:
I want to pass the output received example: (product) to another
function. Would that be done in the .forEach part? I don't want to
print it there
不,在这种情况下,您可以将结果收集到列表中,然后 return 例如:
public List<String> myFunction(List<Map<String, List<String>>> filters){
return filters.stream()
.flatMap(c -> c.keySet().stream())
.collect(Collectors.toList());
}
然后就可以这样食用了:
List<String> result = myFunction(filters);
result.forEach(System.out::println);
我有以下结构:
List<Map<String, List<String>>> filters
考虑以下示例:
filters=[{product=[A1, A2, A3]}]
我只想显示地图键而不是值。
预期输出:
product
我尝试了以下方法:
String op = filters.get(i).keySet().toString();
这给了我以下输出:
[product]
我也尝试过使用 .stream(),但没有用。我只想显示键(一个或多个),即在这种情况下:product
如有任何帮助,我们将不胜感激。
这应该可以解决问题
List<String> collect = filters.stream()
.flatMap(entry ->
entry.keySet().stream())
.collect(Collectors.toList());
collect 将拥有地图的所有键。
您可以使用:
filters.stream().flatMap(c -> c.keySet().stream())
.forEach(System.out::println);
编辑:
I want to pass the output received example: (product) to another function. Would that be done in the .forEach part? I don't want to print it there
不,在这种情况下,您可以将结果收集到列表中,然后 return 例如:
public List<String> myFunction(List<Map<String, List<String>>> filters){
return filters.stream()
.flatMap(c -> c.keySet().stream())
.collect(Collectors.toList());
}
然后就可以这样食用了:
List<String> result = myFunction(filters);
result.forEach(System.out::println);