Issue
I have a file with a various figures like this:
SQUARE;10
SQUARE;20
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());
Answered By - talex Answer Checked By - Clifford M. (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.