The only thing you need from both enums in this code:
Arrays.stream(Action.values()).forEach(e ->{
if(e.getValue().equalsIgnoreCase(sp)){
//System.out.println(sp); Some work to do here
}
} );
is the getValue
method.
So you can create an interface that has this method:
interface HasValue {
String getValue();
}
Make both enums implement the interface:
public enum Action implements HasValue {
...
}
public enum Days implements HasValue {
...
}
Then you can write a generic method:
public <T extends HasValue> void foo(T[] values, String sp) {
Arrays.stream(values).forEach(e ->{
if(e.getValue().equalsIgnoreCase(sp)){
//System.out.println(sp);
}
});
}
You can call it like this:
foo(Action.values(), sp);
foo(Days.values(), sp);
The method doesn't actually have to be generic. You could just do:
public void foo(HasValue[] values, String sp) {
...
}
If you can't change Days
or Action
, you can use a functional interface instead:
public <T> void foo(T[] values, Function<T, String> getValue, String sp) {
Arrays.stream(values).forEach(e ->{
if(getValue.apply(e).equalsIgnoreCase(sp)){
//System.out.println(sp);
}
});
}
// usage:
foo(Action.values(), Action::getValue, sp);
foo(Days.values(), Days::getValue, sp);
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…