I have a List of Enum values like MON, TUE, WED, etc., same need to convert to comma-separated String. Need to use Java 8 to convert the same in an efficient way. For example.
Arrays.stream(Days.values())
.map(MON -> TimeRangeConstants.MON)
.collect(Collectors.joining(","));
enum Days {
MON, TUE, WED, THU, FRI, SAT, SUN;
}
main() {
Days v1 = Days.MON;
Days v2 = Days.WED;
Days v3 = Days.FRI;
List<Days> days = new ArrayList<>();
days.add(v1);
days.add(v2);
days.add(v3);
String str = convertToString(days);
}
convertToString(List<Days> list) {
// need to return String as "Monday, Wednesday, Friday"
}
For the given above example, I need output as "Monday, Wednesday, Friday"
You would have to edit the enum to:
enum Days {
MON("Monday"), TUE("Tuesday"), WED("Wednesday")
;
private String val;
Days(String val) {
this.val = val;
}
@Override
public String toString() {
return val;
}
}
If you have access to the newer stream() method, you can do this:
final String s = String.join(",", list.stream().map(Object::toString).collect(Collectors.toList());
System.out.println("s = " + s);
You can declare a new method in the enum to map the day to the name of the day and then use the java-8 streams like this:
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class DaysToCsv {
enum Days {
MON, TUE, WED, THU, FRI, SAT, SUN;
public static String getFullName(Days day) {
switch (day) {
case MON:
return "Monday";
case TUE:
return "Tuesday";
case WED:
return "Wednesday";
case THU:
return "Thursday";
case FRI:
return "Friday";
case SAT:
return "Saturday";
case SUN:
return "Sunday";
default:
throw new IllegalArgumentException("Unexpected day");
}
}
}
public static void main(String[] args) {
Days v1 = Days.MON;
Days v2 = Days.WED;
Days v3 = Days.FRI;
List<Days> days = new ArrayList<>();
days.add(v1);
days.add(v2);
days.add(v3);
String str = convertToString(days);
System.out.println(str);
}
public static String convertToString(List<Days> list) {
return list.stream().map(day -> Days.getFullName(day)).collect(Collectors.joining(", "));
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With