Skip to content

Instantly share code, notes, and snippets.

@liviutudor
Created April 1, 2017 00:56
Show Gist options
  • Save liviutudor/9ffd601c9ce24342925344dccc27ba83 to your computer and use it in GitHub Desktop.
Save liviutudor/9ffd601c9ce24342925344dccc27ba83 to your computer and use it in GitHub Desktop.
Find by name, extract salary and compute max in java, no streams
public Optional<Double> max(Collection<Double> collection) {
if (collection == null || collection.isEmpty()) return Optional.empty();
Iterator<Double> iter = collection.iterator();
Double max = iter.next();
while (iter.hasNext()) {
Double n = iter.next();
if (n > max) max = n;
}
return Optional.of(max);
}
public Collection<Employee> findName(Collection<Employee> collection, String name) {
List<Employee> list = new ArrayList<>();
if (collection == null || collection.isEmpty()) return list;
for (Employee e : collection) {
if (e.firstName.equals(name)) list.add(e);
}
return list;
}
public Collection<Double> extract(Collection<Employee> collection) {
Collection<Double> list = new ArrayList<>();
if (collection == null || collection.isEmpty()) return list;
for (Employee e : collection) {
list.add(e.salary);
}
return list;
}
// usage
double sal = max(extract(findName(collection, "Bob")));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment