0

I'm trying to migrate an application from Python to Java, which I'm a complete noob, but I have encountered a problem.

In python I receive bytes through the serial ports and I'm able to split the data in a single line by doing just like so:

temp = temp.decode("utf-8").split(',')

Example data:

S,24,31479873,00000,00000,00000,3296,

So it'd be divided to a list of elements, like so:

['S', '24', '31479873', '00000', '00000', '00000', '3296', '\r\n']

And I'd be able to loop through a key list and relate that list to this split list. Appending the result to a list of dictionaries called "packages".

key = ["type", "line_number", "timestamp", "hits", "pulses", "hits_acc", "voltage", "unused"]
self.packages.append({key[i]:temp[i] for i in range(len(key))})

I want the exact same functionality in Java. Can anyone guide me through this? Sorry if I'm being too vague but I'm a complete beginner when it comes to Java.

1
  • Looks like you're trying to create a csv structure keyed by column name. You could either roll your own using Map<String, List<String>> (keys are column headers, values are a list of column values) or use a csv API such as OpenCSV, which generally allow the data columns to be accessed using the column header as a key Commented Sep 8, 2022 at 23:31

1 Answer 1

1

Java is strong typed language , so the code may seems a little complex, as follows:

String line = "S,24,31479873,00000,00000,00000,3296,x";
        String [] parts = line.split(",");
        String [] cols = {"type", "line_number", "timestamp", "hits", "pulses", "hits_acc", "voltage", "unused"};
        if (parts.length != cols.length) {
            System.out.println("Data invalid");
            System.exit(-1);
        }
        Map<String, String> result = new HashMap<>();
        for (int i = 0; i < cols.length; i++) {
            String key = cols[i];
            String val = parts[i];
            result.put(key, val);
        }
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! I implemented this using a Stringbuffer since I'm receiving data from a serial interface. I think it'll work porperly now!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.