我有一个枚举
public enum UnitSystem {
ImperialSystem("Imperial", "in.", 1),
MetricSystem("Metric", "cm.", 2.54);
private String unitSystemName;
private String lengthSuffix;
private double lengthCoeff;
我正在尝试获得String[] l
{"Imperial", "Metric"};
,其中unitSystemName
是一个包含每个系统String[] l = Arrays.stream(UnitSystem.values()).map(UnitSystem::name).collect(Collectors.toList()).toArray(new String[UnitSystem.values().length]);
的数组。现在我最好的选择是:
table_alias.SUM(column_name)
有没有更好的方法来实现它?
答案 0 :(得分:2)
您必须查看枚举值某处并从中提取名称,无论是在内容的代码中,如Calvin的回答建议还是外部像你一样。我无法解决这个问题(至少我无法想到)。
但是你的代码可能会被清理干净。没有理由将流收集到列表然后将其转换为数组 - 您可以直接将其转换为数组:
String[] l =
Arrays.stream(UnitSystem.values()).map(UnitSystem::name).toArray(String[]::new);
答案 1 :(得分:0)
public enum UnitSystem {
ImperialSystem("Imperial", "in.", 1),
MetricSystem("Metric", "cm.", 2.54);
UnitSystem(String unitSystemName, String lengthSuffix, double lengthCoeff) {
this.UNITE_SYSTEM_NAME = unitSystemName;
this.LENGTH_SUFFIX = lengthSuffix;
this.LENGTH_CO_EFF = lengthCoeff;
}
private final String UNITE_SYSTEM_NAME;
private final String LENGTH_SUFFIX;
private final double LENGTH_CO_EFF;
public static String[] getNames() {
String[] strings = new String[UnitSystem.values().length];
short count = 0;
for (UnitSystem s : UnitSystem.values()) {
strings[count] = s.getName();
count++;
}
return strings;
}
public String getName() {
return UNITE_SYSTEM_NAME;
}
public String getLengthSuffix() {
return LENGTH_SUFFIX;
}
public double getLengthCoeff() {
return LENGTH_CO_EFF;
}
}
通过使用getter方法为每个UnitSystem实例完成枚举,我们可以创建一个静态方法,返回所有这些枚举名称数据的String数组。希望这有帮助!
答案 2 :(得分:0)
为unitSystemName
声明一个getter,并使用toArray(String[]::new)
将Stream<String>
转换为String[]
。
public enum UnitSystem {
...
UnitSystem(String unitSystemName, String lengthSuffix, double lengthCoeff) {
this.unitSystemName = unitSystemName;
...
}
public String getUnitSystemName() {
return unitSystemName;
}
public static String[] getNames() {
return Arrays.stream(UnitSystem.values())
.map(UnitSystem::getUnitSystemName)
.toArray(String[]::new);
}
}
答案 3 :(得分:0)
创建静态数组名称只允许在类加载器加载类时加载一次。如果有可能你会不止一次地引用这个列表,那将是理想的。
public enum UnitSystem
{
ImperialSystem("Imperial", "in.", 1), MetricSystem("Metric", "cm.", 2.54);
private String unitSystemName;
private String lengthSuffix;
private double lengthCoeff;
private static String[] names = Arrays.stream(UnitSystem.values())
.map(UnitSystem::name).toArray(String[]::new);
UnitSystem(String unitSystemName, String lengthSuffix, double lengthCoeff)
{
this.unitSystemName = unitSystemName;
this.lengthSuffix = lengthSuffix;
this.lengthCoeff = lengthCoeff;
}
public static String[] getNames()
{
return names;
}
public String getUnitSystemName()
{
return unitSystemName;
}
public String getLengthSuffix()
{
return lengthSuffix;
}
public double getLengthCoeff()
{
return lengthCoeff;
}
}