Reputation: 406
I am trying to use guava's getIfPresent()
for an enum as below:
private enum LegalColumns
{
PRODUCERS_CUT("PRODUCER'S CUT", PMCColumnsEnum.NETWORK_CUT_1.getColumnName()),
PROPOSED_LOCKED_CUT("PROPOSED LOCKED CUT", PMCColumnsEnum.NETWORK_CUT_3.getColumnName()),
LOCK("LOCK", PMCColumnsEnum.LOCKED_DELIVERY.getColumnName()),
FINAL_MIX("FINAL MIX", PMCColumnsEnum.MIX_DATE.getColumnName());
private String column;
private String replacementColumn;
LegalColumns(String column, String replacementColumn) {
this.column = column;
this.replacementColumn = replacementColumn;
}
public static LegalColumns getIfPresent(String column) {
System.out.println(Enums.getIfPresent(LegalColumns.class, column.trim().toUpperCase()));
return Enums.getIfPresent(LegalColumns.class, column.toUpperCase()).orNull();
}
}
When I step through this however, it always prints out Optional.absent()
despite the strings being exact matches. I followed, to my knowledge, the guava spec exactly. Any ideas what I am missing?
Upvotes: 0
Views: 476
Reputation: 4470
Returns an optional enum constant for the given type, using Enum.valueOf(java.lang.Class, java.lang.String). If the constant does not exist, Optional.absent() is returned. A common use case is for parsing user input or falling back to a default enum constant. For example, Enums.getIfPresent(Country.class, countryInput).or(Country.DEFAULT);
Returns the enum constant of the specified enum type with the specified name. The name must match exactly an identifier used to declare an enum constant in this type. (Extraneous whitespace characters are not permitted.)
From your comment
I have gone with another approach, but for others, I passed in columns like "FINAL MIX".
"FINAL MIX" != "FINAL_MIX"
Guava uses the enum identifier, not the string you pass into the constructor.
So for the enum instance, FINAL_MIX("FINAL MIX", PMCColumnsEnum.MIX_DATE.getColumnName());
the enum identifier is "FINAL_MIX" not the string you pass in "FINAL MIX"
IN ADDITION! as you do not define a Locale on your string.toUpperCase, you are at risk of the turkey I bug.
Upvotes: 1