Skip to main content

Generating CSV export [Resolved]

I created a CSV export that works like the code below. There is a LinkedHashMap where the keys are the column title and values are functions where certain properties are read.

By reording the lines where entries are added to the map, one also reorders the csv column representation. Column header and data are connected so that one can't move one without the other.

Are there any downsides with my code? Is there a better approach? (I omitted escaping characters and so on to reduce code)

public class Test {

    private final static Map> DEF_MAP = new LinkedHashMap<>();

    public static void main(String[] args) {
        DEF_MAP.put("Prop B", bean -> bean.getB());
        DEF_MAP.put("Prop A", bean -> bean.getA());

        List beans = new ArrayList<>();
        Bean a = new Bean();
        a.setA("a1");
        a.setB("b1");
        beans.add(a);

        Bean b = new Bean();
        b.setA("a2");
        b.setB("b2");
        beans.add(b);

        DEF_MAP.keySet().forEach(k -> {
            System.out.print(k + ";");
        });
        System.out.println();

        beans.forEach(bean -> {
            DEF_MAP.values().forEach(v -> {
                System.out.print(v.apply(bean) + ";");
            });
            System.out.println();
        });
    }

    private static class Bean {
        private String a;
        private String b;

        public String getA() {
            return a;
        }

        public void setA(String a) {
            this.a = a;
        }

        public String getB() {
            return b;
        }

        public void setB(String b) {
            this.b = b;
        }

    }
}

Question Credit: user489872
Question Reference
Asked January 11, 2019
Tags: java
Posted Under: Programming
13 views
1 Answers

There is a #codereview site, which might be better suited to your question format.

However! architecturally it has a few problems

First and foremost you have not separated out the code that writes the CSV into its own class. You need to do this and publish the code as a library.

Once you have done that you can address the other problems.

  1. You have no way of specifying the separator character to use
  2. You have no way of specifying different output streams
  3. You don't address escaping. I know you say why, but this is a huge part of CSV output.
  4. It's a lot of work for someone using the code to set up all the fields. I would want a default which automatically detected the public fields and used them in the order they appear on the Object array I pass in.
  5. I would also want to specify the default formats for numbers, dates etc

credit: Ewan
Answered January 11, 2019
Your Answer
D:\Adnan\Candoerz\CandoProject\vQA