Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to create different objects from a List of Strings?

I have a file with a various figures like this:

SQUARE;10

SQUARE;20

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

RECTANGLE;10;30

CIRCLE;10

After adding the lines to the String List, I would like it to create all the objects after one run through the list. how to do it when, for example, a rectangle has two parameters and the rest only one?

So far this is my code which works but it is buggy, because for each type of figure I have to go through the list again, I also can’t use switch for this task.

    BufferedReader br = new BufferedReader(new FileReader("figury.txt"));
    List<List<String>> list1 = new ArrayList<>();
    String s;
    while ((s = br.readLine()) != null) {
        List<String> list = Arrays.asList(s.split(";"));
        list1.add(list);

    }
    list1.stream().filter(k -> k.contains("SQUARE")).forEach(i -> new Square(Integer.parseInt(i.get(1))));
    list1.stream().filter(k -> k.contains("CIRCLE")).forEach(i -> new Circle(Integer.parseInt(i.get(1))));
    list1.stream().filter(k -> k.contains("RECTANGLE")).forEach(i -> new Rectangle(Integer.parseInt(i.get(1)), Integer.parseInt(i.get(2))));

All figures are subClasses of abstract class Figure

>Solution :

Try this

        Map<String, Function<List<String>, Figure>> converters = new HashMap<>();
        converters.put("SQUARE", l -> new Square(Integer.parseInt(l.get(1))));
        // Repeat for each shape

        List<Figure> list = list1.stream().map(l -> converters.get(l.get(0)).apply(l))
                .collect(Collectors.toList());
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading