I need something like a 3-dimension (like a list or a map), which I fill with 2 Strings and an Integer within a loop. But, unfortunately I don't know which data structure to use and how.
// something like a 3-dimensional myData
for (int i = 0; i < 10; i++) {
myData.add("abc", "def", 123);
}
A Google's Guava code would look like this:
import com.google.common.collect.Table;
import com.google.common.collect.HashBasedTable;
Table<String, String, Integer> table = HashBasedTable.create();
for (int i = 0; i < 10; i++) {
table.put("abc", "def", i);
}
Code above will construct a HashMap inside a HashMap with a constructor that looks like this:
Table<String, String, Integer> table = Tables.newCustomTable(
Maps.<String, Map<String, Integer>>newHashMap(),
new Supplier<Map<String, Integer>>() {
@Override
public Map<String, Integer> get() {
return Maps.newHashMap();
}
});
In case you want to override the underlying structures you can easily change it.
Create an object that encapsulates the three together and add them to an array or List:
public class Foo {
private String s1;
private String s2;
private int v3;
// ctors, getters, etc.
}
List<Foo> foos = new ArrayList<Foo>();
for (int i = 0; i < 10; ++i) {
foos.add(new Foo("abc", "def", 123);
}
If you want to insert into a database, write a DAO class:
public interface FooDao {
void save(Foo foo);
}
Implement as needed using JDBC.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With