Reputation: 259
I'm using Java 8 and I can get the max
and min
. Works great but I need to check also the max
and min
of 10 more properties (e.g., User
age, prop1, prop2, prop3, etc...).
How can I do it this instead of replicate the same code 10 times?
IntSummaryStatistics summaryStatistics = data.stream()
.mapToInt(User::getProp2)
.summaryStatistics();
int max = summaryStatistics.getMax();
int min = summaryStatistics.getMin();
And normalize the data between 0 and 5
data.stream().forEach(d -> {
d.setNormalized(5 * ((d.getProp2() - min) / (max - min));)
});
Upvotes: 2
Views: 125
Reputation: 51403
You can try the good old method refactoring in combination with the ToIntFunction interface
public static void normalization(Collection<User> data, ToIntFunction<User> getProp) {
IntSummaryStatistics summaryStatistics = data.stream()
.mapToInt(getProp)
.summaryStatistics();
int max = summaryStatistics.getMax();
int min = summaryStatistics.getMin();
data.forEach(d -> d.setNormalized(5 * ((getProp.applyAsInt(d) - min) / (max - min))));
}
The parameter ToIntFunction<User> getProp
is for the "age, prop1, prop2, prop3" part.
To call the method:
normalization(data, User::getProp2);
Upvotes: 2