• 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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Using Comparator with Lambda

 
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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: 41860
908
Eclipse IDE VI Editor Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
"How many licks ..." - I think all of this dog's research starts with these words. Tasty tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic