我有以下数据类型的数据结构如下:
Name Type
Keyval String //This is the key element
x Float
x2 Float
result Float
performance String
我想将其存储到HashMap
,其中Key为keyval
,其他所有信息(x,x2,result,performance
)为相应的keyval
。
输出示例:
[Keyval=com.a.service, x=0.05, x2=0.07, result=0.02, performance = IMPROVED]
[Keyval=com.b.service, x=0.03, x2=0.07, result=0.04, performance = IMPROVED]
[Keyval=com.c.service, x=0.15, x2=0.07, result=0.08, performance = DEGRADED]
如何存储它以及如何访问它?
答案 0 :(得分:2)
您需要将所有元素存储在类(和构造函数)中:
public class Element {
float x;
float x2;
float result;
String performance;
public Element(float x, float x2, float result, String performance) {
this.x = x;
this.x2 = x2;
this.result = result;
this.performance = performance;
}
@Override
public String toString() {
return "Element{" + "x=" + x + ", x2=" + x2 + ", result=" + result + ", performance=" + performance + '}';
}
}
要像这样使用:
public static void main(String[] args) {
HashMap<String, Element> map = new HashMap<String, Element>();
map.put("com.a.service", new Element(0.05, 0.07, 0.02, "IMPROVED"));
//...
Element a = map.get("com.a.service"); //x=0.05, x2=0.07, result=0.02, performance = IMPROVED
}
取回元素;)
答案 1 :(得分:1)
您可以拥有Map<String, CustomObject> map
类型的地图。您的CustomObject
POJO看起来像;
public class CustomObject {
Float x;
Float x2;
Float result;
String performance;
// constructor , setter and getters
}
您可以检索调用值
CustomObject object = map.get('keyValue');
答案 2 :(得分:1)
您可以这样做:
import java.util.HashMap;
import java.util.Map;
public class Value{
String performance;
float x, x2, result;
public Value(float x, float x2, float result, String performance) {
this.performance = performance;
this.x = x;
this.x2 = x2;
this.result = result;
}
public static void main(String[] args) {
Map<String, Value> map = new HashMap<>();
// to add values
map.put("com.a.service", new Value(0.03f, 0.07f, 0.04f, "IMPROVED"));
// to access them
Value value = map.get("com.a.service");
System.out.printf("KeyValue= com.a.service , X= %.2f, X2= %.2f, Result= %.2f, Performance= %s",
value.x, value.x2, value.result, value.performance );
}
}
<强>输出强>
KeyValue= com.a.service , X= 0.03, X2= 0.07, Result= 0.04, Performance= IMPROVED
答案 3 :(得分:0)
创建一个包含以下私有字段变量的类WrapperClass
:
x Float
x2 Float
result Float
performance String
和构造函数:
public WrapperClass(Float x, Float x2, Float result, String performance) {
this.x = x;
this.x2 = x2;
this.result = result;
this.performance = performance;
}
然后定义Map<KeyVal, WrapperClass> myMap = new HashMap<>();
myMap.put("com.a.service", new WrapperClass(0.5,0.07,0.02,IMRPOVED));
myMap.put("com.b.service", new WrapperClass(0.03,0.07,0.04,IMRPOVED));
依旧......
现在您可以获得myMap.get("com.a.service")
,它将返回WrapperClass
个对象。
我希望这能回答你的问题。