[英]Convert Enum list to comma separated String with matching Enum value
I have a List of Enum values like MON, TUE, WED, etc., same need to convert to comma-separated String.我有一个枚举值列表,如 MON、TUE、WED 等,同样需要转换为逗号分隔的字符串。 Need to use Java 8 to convert the same in an efficient way.
需要使用 Java 8 以有效的方式进行转换。 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 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:您可以在枚举中声明一个新方法来将日期映射到日期名称,然后像这样使用 java-8 流:
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(", "));
}
}
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:如果您有权访问较新的 stream() 方法,则可以执行以下操作:
final String s = String.join(",", list.stream().map(Object::toString).collect(Collectors.toList());
System.out.println("s = " + s);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.