i具有<String, List<Object>>
类型的Map
,其中该Map
的键是与包含X和Y坐标的Object
关联的名称(String
)。
示例:
Names (String) Coordinates
Cord1 [[0.1,0.1,0.1],[0.2,0.3,0.4]]
Cord1,Cord2 [[0.1,0.1] ,[0.4,0.5]]
Cord1,Cord2,Cord3 [[0.1,0.1] ,[0.6,0.7]]
我要实现的是在有逗号,
时拆分名称,这样我只能有单个名称,这也会影响坐标并避免重复。
我想实现的示例:
Cord1 [[0.1,0.1,0.1,0.1,0.1,0.1],[0.2,0.3,0.4,0.5,0.6,0.7]]
Cord2 [[0.01,0.01,0.01,0.01] ,[0.4,0.5,0.6,0.7]]
Cord3 [[0.01,0.01] ,[0.6,0.7]]
有办法做到这一点吗?
编辑:
我对Java 8并不熟悉,这显然是最佳的方法,但是我正在尝试沿着这些行为尚未工作的某些东西:
List<String> list = Splitter.on(',').splitToList(value);
for (String element : list) {
//TO-DO
}
电源对象:
public class Cord {
private double X;
private double Y;
private String name;
public Cord(double x, double y, String name) {
this.X=x;
this.Y=y;
this.name=name;
}
@Override
public String toString() {
return "["+X+","+Y+"]";
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getX() {
return X;
}
public void setX(double x) {
X = x;
}
public double getY() {
return Y;
}
public void setY(double y) {
Y = y;
}
}
java-9的flatMapping
有流方式:
import static java.util.stream.Collectors.*;
Map<String, List<Object>> collect = map.entrySet().stream()
.flatMap(entry -> Arrays.stream(entry.getKey().split(","))
.map(s -> new AbstractMap.SimpleEntry<>(s, entry.getValue())))
.collect(groupingBy(Map.Entry::getKey,
flatMapping(entry -> entry.getValue().stream(), toList())));
如果您不能使用Java-9,它仍然可以通过流API来完成,但它的措辞会更加多。可能在这种情况下,您应该考虑使用循环的解决方案。
Map<String, List<Object>> collect1 = map.entrySet().stream()
.flatMap(entry -> Arrays.stream(entry.getKey().split(","))
.map(s -> new AbstractMap.SimpleEntry<>(s, entry.getValue())))
.collect(groupingBy(Map.Entry::getKey, mapping(Map.Entry::getValue, toList())))
.entrySet().stream()
.flatMap(entry -> entry.getValue().stream()
.flatMap(Collection::stream)
.map(o -> new AbstractMap.SimpleEntry<>(entry.getKey(), o)))
.collect(groupingBy(Map.Entry::getKey, mapping(Map.Entry::getValue, toList())));
这是我从您的问题中理解的解决方案:
Map<String, List<Object>> doTheThing(Map<String, List<Object>> input){
Map<String, List<Object>> retr = new Map<String, List<Object>>();
for(String s1:input.keySet()){//for each Name on the original map
String[] separatedByCommas = s1.split(",");//split the names by ","
for(String s2:separatedByCommas){//for each separated by "," name
if(!retr.containsKey(s2)){
//if the separated by "," name is not on the retr map just put to the separated by "," name the contents of name
retr.put(s2,input.get(s1));
}else{
//if the separated by "," name is on the retr map add to the separated by "," name the contents of name
retr.put(s2,retr.get(s2).addAll(input.get(s1));//add to whats already in s2
}
}
return retr;
}