问题描述
在Java中将多个列的组合创建到由值和列名的组合组成的数组对象中?
这样每个对象都将包含Object (column name,value)
的数组。
我已通过该列内的列名和值存储了信息。 例如:
Region Store State
west Reliance california
east Dmart newyork
基本上,上面的JSON结构如下
[
{
"type": "Region",//more fields
"filterValues": [
{
"name": "west"
//more fields
},{
"name": "east"
}
]
},{
"type": "Store","filterValues": [
{
"name": "Reliance"
},{
"name": "Dmart"
}
]
},{
"type": "State","filterValues": [
{
"name": "california"
},{
"name": "newyork"
}
]
}
]
如何将上述结构转换为以下组合:
Region west | Store Reliance | State california
Region west | Store Reliance | State newyork
Region west | Store Dmart | State california
Region west | Store Dmart | State newyork
.
.
.
所以Object结构如下。
[
{
"values": [
{
"type": "Region","name": "west"
},{
"type": "Store","name": "Reliance"
},{
"type": "State","name": "california"
}
]
},{
"values": [
{
"type": "Region","name": "newyork"
}
]
}
]
如何实现此数据结构?
我尝试先创建地图,其中列名称将为key
,并且该列中的值将作为value
的一部分,
Map<String,List<String>> typeBOsMap = attributes
.stream()
.collect(Collectors.toMap(Attribute::getType,attribute -> attribute.getFilterValues()
.stream()
.map(AttributeFilters::getFilterValue)
.collect(Collectors.toList()))
);
但是在此之后,我仍然停留在如何从该地图创建组合的地方?
解决方法
首先,将typeBOsMap
转换为List<Map.Entry<String,List<String>>>
List<Map.Entry<String,List<String>>> list = typeBOsMap.entrySet().stream().collect(Collectors.toList());
然后递归置换所有可能的组合
List<List<Map.Entry<String,String>>> permute(List<Map.Entry<String,List<String>>> list,int index,List<Map.Entry<String,String>> now) {
if (index >= list.size()) {
return Arrays.asList(now);
}
Map.Entry<String,List<String>> entry = list.get(index);
List<List<Map.Entry<String,String>>> res = new ArrayList<>();
for (String value : entry.getValue()) {
List<Map.Entry<String,String>> newList = new ArrayList<>(now);
newList.add(new AbstractMap.SimpleEntry<>(entry.getKey(),value));
res.addAll(permute(list,index + 1,newList));
}
return res;
}
您可以使用list
List<List<Map.Entry<String,String>>> data = permute(list,Collections.emptyList());
输出:
[State=california,Region=west,Store=Reliance]
[State=california,Store=Dmart]
[State=california,Region=east,Store=Dmart]
[State=newyork,Store=Reliance]
[State=newyork,Store=Dmart]
在线演示here