如何使用Java创建csv文件中具有相同行名称的所有值的列表

ar5n3qh5  于 2022-12-15  发布在  Java
关注(0)|答案(2)|浏览(162)

Excel file I'm using
我想解析一个csv文件并提取名字,比如'chair',然后是每种可能颜色的列表,比如['Blue','Green','Yellow']。我该怎么做呢?
我创建了一个类Object,它有一个'String name'和一个'Listcolors'。

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);
            }
vwoqyblh

vwoqyblh1#

您可以创建一个Hashmap,其中key作为项目的名称,value作为可用颜色的列表。
我希望下面的片段能解决你的问题。祝你好运!!

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);
        }
    }
2lpgd968

2lpgd9682#

@g00se什么叫“流分组操作”
实际上,在您的例子中,由于您使用了正确的csv API,您可以利用它先创建bean,然后再进行分组。下面是我所说的流分组的含义:我们创建一个Map<String, HouseholdObject>>(是的,这是我给你的实体起的名字--可惜里面有“object”这个词,但没关系),它把它们收集到同名的组中:

package com.technojeeves.opencsvbeans;

import com.opencsv.bean.CsvToBeanBuilder;
import java.util.List;
import java.util.Map;
import static java.util.stream.Collectors.*;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

public class HouseholdParser {
    public static void main(String[] args) {
        try {
            List<HouseholdObject> objects = new HouseholdParser().read(new File(args[0]));
            Map<String, List<HouseholdObject>> objectsGroupedByName = 
            objects.stream()
                .skip(1)
                .collect(groupingBy(HouseholdObject::getName));
            System.out.println("The following groups of household objects were found:");
            objectsGroupedByName.entrySet()
                .stream()
                .forEach(e -> {
                    System.out.println(e.getKey());
                    e.getValue()
                        .stream()
                        .forEach(v -> System.out.printf("\t%s%n", v.getColour()));
                });

        } catch (Throwable t) {
            t.printStackTrace();
        }
    }

    public List<HouseholdObject> read(File file) {
        try (FileReader reader = new FileReader(file)) {
            return new CsvToBeanBuilder(reader).withType(HouseholdObject.class).build().parse();
        } catch (IOException e) {
            throw new RuntimeException("Cannot read file: " + file.getName() + e);
        }
    }
}

这是我做的豆子

package com.technojeeves.opencsvbeans;

import com.opencsv.bean.CsvBindByPosition;
import com.opencsv.bean.CsvCustomBindByPosition;
import com.opencsv.bean.AbstractBeanField;
import com.opencsv.bean.CsvRecurse;

public class HouseholdObject {
    @CsvBindByPosition(position = 0)
    private String name;
    @CsvBindByPosition(position = 1)
    private String colour;

    public HouseholdObject() {
    }

    public HouseholdObject(String name, String colour) {
        this.name = name;
        this.colour = colour;
    }

    public String getName() {
        return this.name;
    }

    public String getColour() {
        return this.colour;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setColour(String colour) {
        this.colour = colour;
    }

    @Override
    public String toString() {
        return String.format("%s=%s,%s=%s", "name", name, "colour", colour);
    }

    @Override
    public boolean equals(Object o) {
        HouseholdObject other = (HouseholdObject)o;
        return name.equals(other.name) && colour.equals(other.colour);
    }

    @Override
    public int hashCode() {
        return name.hashCode() * colour.hashCode();
    }
}

下面是我使用源CSV的输出:

The following groups of household objects were found:
Table
     Purple
     Pink
Chair
     Blue
     Green
     Yellow
Door
     Yellow

相关问题