• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Junilu Lacar
  • Jeanne Boyarsky
  • Bear Bibeault
Sheriffs:
  • Knute Snortum
  • Tim Cooke
  • Devaka Cooray
Saloon Keepers:
  • Ron McLeod
  • Stephan van Hulst
  • Tim Moores
  • Tim Holloway
  • Carey Brown
Bartenders:
  • Piet Souris
  • Frits Walraven
  • Ganesh Patekar

Using Comparator with Lambda

 
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

package chapter3.page149;

import chapter3.page143.Duck;

public class Squirrel {
private int weight;
private String species;
public Squirrel(String theSpecies, int weight) {
if (theSpecies == null) throw new IllegalArgumentException();
species = theSpecies;
this.weight = weight;
}

public int getWeight() { return weight; }
public void setWeight(int weight) { this.weight = weight; }
public String getSpecies() { return species; }
}

package chapter3.page149;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class ChainingComparator implements Comparator<Squirrel> {

public int compare(Squirrel s1, Squirrel s2) {
Comparator<Squirrel> c = Comparator.comparing(s -> s.getSpecies());
c = c.thenComparingInt(s -> s.getWeight());
return c.compare(s1, s2);
}

public static void main(String[] args) {
List<Squirrel> squirrels = new ArrayList<>();
squirrels.add(new Squirrel("Test 1", 26));
squirrels.add(new Squirrel("Test 1", 10));
squirrels.add(new Squirrel("Test 2", 45));
Collections.sort(squirrels);
}

}

The Collections.sort(squirrels) doesn't compile... Why is that?
 
author & internet detective
Posts: 39530
776
Eclipse IDE VI Editor Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Roderick,
There are two method signatures for sort(). The first does not take a Comparator; just a list. That's the one you are calling. In order for that one to compile, the class (Squirrel) must implement Comparable.

The second takes a Comparator and allows any generic type to be in the list. So this compiles:


Also a tip with the code tags: highlight what you want in code before clicking the code button. That makes it look like mine.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!