'String.format() for multiple attributes in the same row
I am trying to compress my code and I get four String.format() in the same line. Is there a way to do it in a cleaner and more simple way?
My code block:
String startX = String.format("%03d", mission.getStartX());
String startY = String.format("%03d", mission.getStartY());
String endX = String.format("%03d", mission.getEndX());
String endY = String.format("%03d", mission.getEndY());
Thanks :)
Solution 1:[1]
The only way I can see to tidy up a bit, to have a DRY (don't repeat yourself) code, is to define a method, say format03d() as follow:
private String format03d(int x) {
return String.format("%03d", x);
}
One advantage is that your code is centralized in one place. If one day you want to change the way you convert your decimals to strings, you change it there.
You can then call the method on your variables:
String startX = format03d(mission.getStartX());
String startY = format03d(mission.getStartY());
String endX = format03d(mission.getEndX());
String endY = format03d(mission.getEndY());
I assume that your variables are integers.
If you want to go down the road of collections, you can use streams.
Stream.of(
mission.getStartX(),
mission.getStartY(),
mission.getEndX(),
mission.getEndY())
.map(x -> String.format("%03d", x))
.collect(Collectors.toList())
This will give you a list of your formatted integers.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
