我有一个数组类型String []
1.name_of_product='TV', SKU='PRDCT-1-1', quantity='1',...
2.name_of_product='PC', SKU='PRDCT-2-2', quantity='2',...
3.name_of_product='Tablet', SKU='PRDCT-3-10', quantity='10',...
和HashMap myArray = [value1,value2,value3,..,valueX]
Map<String, String>
我的目标是从myHashMap = {field1=value2,value3, field2=value1,value2,value3, ..., fieldN=value1,value2}
中删除myArray
中与myHashMap(field1)
中的值相比不存在的值。在上面的示例中,它将是myHashMap(field2)
。
如何解决这个问题?我曾尝试过这样的事情:
value1
field1
和field2
密钥
myHashMap
field2
PS。 我仅限于Java 7
答案 0 :(得分:1)
List<String> f = Arrays.asList(myHashMap.get("field1").split(","));
List<String> s = Arrays.asList(myHashMap.get("field2").split(","));
List<String> result = s.stream().filter(v -> !f.contains(v))
.collect(Collectors.toList());
myArray.removeAll(result);
这是一个直接的解决方案。
正如 flakes 所指出的,for循环在这种情况下是多余的,可以用removeAll
来解决。这是一个Java 7解决方案:
//this list is immutable (it's fine)
List<String> first = Arrays.asList(myHashMap.get("field1").split(","));
// we would need a mutable copy of the second one:
List<String> second = new ArrayList<>(Arrays.asList(myHashMap.get("field2").split(",")));
List<String> myList = new ArrayList<>(Arrays.asList(myArray));
second.removeAll(first);
myList.removeAll(second);
// if you need the result back as array:
String[] result = myList.toArray(new String[myList.size()]);
答案 1 :(得分:1)
首先,我将创建一组映射到字段value1..valueX
的映射的所有值field2..fieldN
(我明确排除映射到field1
的值):
Set<String> nonField1Values = new HashSet<>();
for (Map.Entry<String, String> entry : myHashMap.entrySet()) {
if (!entry.getKey().equals("field1")) {
String currentValue = entry.getValue();
List<String> values = Arrays.asList(currentValue.split(","));
nonField1Values.addAll(values);
}
}
nonField1Values
集合包含映射到地图字段的所有值(没有重复元素,因为它是一个集合),但field1
的值除外。
接下来,我将获得field1
的值并从中创建一个集合:
Set<String> field1Values =
new HashSet<>(Arrays.asList(myHashMap.get("field1").split(",")));
以下步骤是为了获得这两组之间的差异:
nonField1Values.removeAll(field1Values);
现在nonField1Values
仅包含nonField1Values
中不存在的field1Values
元素。
最后一步是从数组中创建一个集合并删除nonField1Values
集合中包含的所有元素:
Set<String> result = new HashSet<>(Arrays.asList(myArray));
result.removeAll(nonField1Values);
答案 2 :(得分:0)
以下怎么样?这不是最优雅的方式。可能有更好的答案:
Set<String> s1 = new HashSet<>(Arrays.asList(map.getOrDefault("field1", "").split(",")));
Set<String> s2 = new HashSet<>(Arrays.asList(map.getOrDefault("field2", "").split(",")));
s2.removeAll(s1);
List<String> list = new ArrayList<String>();
for(String str : myArray) {
if(!s2.contains(str))
list.add(str);
}
return list.toArray(new String[0]);