java - Container of objects indexed by definite field -
i have set of objects need index definite field of objects. there sample implementation hashmap (update: actually, hashmap used illustration, not insist container looking surely hashmap)
public class foo { public string id; // field index // other fields number public int i; public double d; public string description; public string rule; public double otherd; public foo(string id, int i, double d, string description, string rule, double otherd) { this.id = id; this.i = i; this.d = d; this.description = description; this.rule = rule; this.otherd = otherd; } }
i need have container of foo
objects indexed unique string field id
. following foohashmap
current solution:
hashmap<string, foo> foohashmap = null; foohashmap.put("bar", foo("bar", 1, 0.3, "aa", "bb", 0.8)); foohashmap.put("tzar", foo("tzar", 8, 12.3, "dlj", "no rule", 0.343)); // etc.
it looks pretty ugly solution doubling id
in foo
constructor , in hashmap key. can java 8 suggest more elegant solution? not mean solution like
public void addfoo(foo foo) { foohashmap.put(foo.id, foo); }
personally use solution have posted @ end:
addfoo(new foo("bar", 1, 0.3, "aa", "bb", 0.8)); addfoo(new foo("tzar", 8, 12.3, "dlj", "no rule", 0.343));
and let addfoo
method handle rest:
public void addfoo(foo foo) { foohashmap.put(foo.id, foo); }
since apparently have create foo
objects anyway can't think of more elegant solution.
if had list of foo
objects, create map this
map<string, foo> foomap = foos .stream() .collect(collectors.tomap(f -> f.id, f -> f));
Comments
Post a Comment