A. Halil
A. Halil

Reputation: 25

Create for element of a CSV a List in Java

I have a question regarding csv and java. I have a csv file with a lot of data. There are for example three different ids, and per id around 5k data points.

The csv is like following: ID, Data1(String), Data2(Long), Data3(Float), Data4(Float), Data5(Float)

I read the csv an store every column to another linked list, so that for ever linked list the index i is one row.

What I want to do is to have a per ID a list of the data.

I have done it so far like this:

LinkedList<String> new_id = new LinkedList();
LinkedList<String> new_data1 = new LinkedList();
LinkedList<String> new_data2 = new LinkedList();
....
....

for(int i = 0; i < id.size(); i++){
    if(id.get(i).equals(String theidiwant){
        new_id.add(id.get(i));
        new_data1.add(data1.get(i));
        ....
        ....
}

So my question would be whether there is a simple solution to create for each id a list of those data.

I hope you understand what I am trying to ask. Sorry for that complicated description.

Cheers!

Upvotes: 0

Views: 950

Answers (3)

Lorenz
Lorenz

Reputation: 1

You might want to try out using a Map.

Map<Integer, List<String>> myMap = new HashMap<Integer, List<String>>();

LinkedList<String> data = new LinkedList<>();

myMap.put([your_key],data);

You can then access the list with the id's like this:

if (myMap.containsKey([your_key])) {
    List<String> list = myMap.get([your_key]);
}

Upvotes: 0

Jotunacorn
Jotunacorn

Reputation: 526

You should start of by creating a class for the rows and have an object representing one row e.g.

public class Row{
    public String id;
    public String data1;
    public long data2;
    public float data3;
    public float data4;
    public float data5;

    public Row(String id, String data1, long data2, float data3, float data4, float data5) {
        //Enter constructor here e.g. this.id = id...
    }
}

You can then filter the objects into a list with

... after parsing the data into List<Row> data;

List<Row> filteredList = data.stream().filter(
    row -> row.id.equals(String theidiwant))
    .collect(Collectors.toCollection(LinkedList::new));

If you want one list per id you can as SpaceCowboy said and create a map with lists

Map<String, List<Row>> mappedValues = new HashMap<>();
for(Row row : data) {
    if(mappedValues.containsKey(row.id) {
        List<Row> values = mappedValues.get(row.id)
        values.add(row)
    }
    else {
        List<Row> newValues = new ArrayList<>();
        newValues.add(row)
        mappedValues.put(row.id, newValues);
    }
}

Upvotes: 3

Ashish Lohia
Ashish Lohia

Reputation: 289

I am not sure why you want to create list of columns, list of rows make much more sense. Although, using java class to map the columns and creating a list of rows will be most appropriate.

Upvotes: 0

Related Questions