Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

3-Dimension List or Map

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);
}
like image 880
Evgenij Reznik Avatar asked May 01 '12 15:05

Evgenij Reznik


2 Answers

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.

like image 65
Tombart Avatar answered Sep 29 '22 10:09

Tombart


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.

like image 38
duffymo Avatar answered Sep 29 '22 11:09

duffymo