Home > Enterprise >  How can I use Java to create a list of all the values from csv file that have the same row name
How can I use Java to create a list of all the values from csv file that have the same row name

Time:12-06

Excel file I'm using

I want to parse a csv file and extract the name, like 'chair' and then a list of each possible colour, so ['Blue','Green','Yellow']. How can I do this?

I have created a class Object, that has a 'String name' and a 'Listcolours'.

 CSVReader reader = new CSVReader(new FileReader(new File(url.toURI()).getAbsolutePath()));
        Object<API> listings = new ArrayList<Object>();

            String [] line;
            List<String> colourList = new ArrayList<>();
           reader.readNext();
            while ((line = reader.readNext()) != null) {
                String name = line[0];
                String colour = line[1];
                colourList.add(operation);
                Object object = new Object(name,colourList);
                listings.add(object);
            }

CodePudding user response:

You can create a Hashmap with key as name of the item and value as list of colors available.

I hope below snippet will solve your problem. Good Luck!!

    HashMap<String,List<String>> data = new HashMap<>();
    String [] line;
    reader.readNext();
    while ((line = reader.readNext()) != null) {
        String name = line[0];
        String colour = line[1];
        if(data.containsKey(name.toLowerCase())){
            data.get(name.toLowerCase()).add(colour.toLowerCase());
        }
        else{
            List<String> colorList = new ArrayList<>();
            colorList.add(colour.toLowerCase());
            data.put(name.toLowerCase(),colorList);
        }
    }
  • Related