Marc Hauschildt
Web Technologies and Computer Software Development Instructor at Kirkwood Community College in Cedar Rapids, IA.
Week 3
Update the President class to implement the Comparable interface to create a natural sort order.
Create Comparator objects to compare by other data.
import java.time.LocalDate;
import java.util.Comparator;
public class President implements Comparable<President> {
// Attributes, constructors, getters, setters, and toString omitted
@Override
public int compareTo(President o) {
// Compares objects by their id (natural sort order)
return this.id - o.id;
// return Integer.valueOf(this.id).compareTo(Integer.valueOf(o.id));
}
// Compares objects by their height (low to high)
public static Comparator<President> compareHeight = Comparator.comparing(President::getHeightInInches).thenComparing(President::getId);
// Compares objects by their weight (low to high)
public static Comparator<President> compareWeight = Comparator.comparing(President::getWeightInPounds).thenComparing(President::getId);
// Compares objects by their dateOfBirth (oldest to youngest)
public static Comparator<President> compareAge = Comparator.comparing(President::getDateOfBirth).thenComparing(President::getId);
}
Write code to get the list of President objects, then sort and display the data.
import java.time.LocalDate;
import java.time.format.DateTimeParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.Collections;
public class PresidentDAO {
private static List<President> presidents = new ArrayList<>();
public static void main(String[] args) {
Collections.sort(list);
printList("Alphabetical A-Z", list);
Collections.reverse(list);
printList("Alphabetical Z-A", list);
// Collections.sort(list, President.compareHeight);
// printList("Shortest 5", list, 5);
// Collections.sort(list, President.compareHeight.reversed());
// printList("Tallest 5", list, 5);
// printOneWithLabel("Shortest", list.stream().min(President.compareHeight).get());
// printOneWithLabel("Tallest", list.stream().max(President.compareHeight).get());
// Collections.sort(list, President.compareWeight);
// printList("Lightest 5", list, 5);
// Collections.sort(list, President.compareWeight.reversed());
// printList("Heaviest 5", list, 5);
// printOneWithLabel("Lightest", list.stream().min(President.compareWeight).get());
// printOneWithLabel("Heaviest", list.stream().max(President.compareWeight).get());
// Collections.sort(list, President.compareAge);
// printList("Oldest 5", list, 5);
// Collections.sort(list, President.compareAge.reversed());
// printList("Youngest 5", list, 5);
// printOneWithLabel("Youngest", list.stream().min(President.compareAge).get());
// printOneWithLabel("Oldest", list.stream().max(President.compareAge).get());
}
public static void printList(String title, List<President> presidents) {
printList(title, presidents, presidents.size());
}
public static void printList(String title, List<President> presidents, int count) {
// The list is printed, formatted as a numbered list, with a title above it.
System.out.println("---------" + title + "---------");
for(int i = 0; i < count; i++) {
System.out.printf("%s) %s, %s\n", (i + 1), presidents.get(i).getLastName(), presidents.get(i).getFirstName());
}
System.out.println();
}
public static void printOneWithLabel(String label, President president) {
// Prints a record with a label in front
System.out.printf("%s: %s, %s\n\n", label, president.getLastName(), president.getFirstName());
}
public static List<President> getPresidents() {
if(presidents.size() == 0) {
getFromCSV();
}
return presidents;
}
private static void getFromCSV() {
List<String> lines = FileInput.readAllLines("presidents.csv");
for(String line: lines) {
String[] president = line.split(",");
try {
int id = Integer.parseInt(president[0].trim());
String firstName = president[1].trim();
String lastName = president[2].trim();
int height = Integer.parseInt(president[3].trim());
double weight = Double.parseDouble(president[4].trim());
LocalDate dateOfBirth = LocalDate.parse(president[5].trim());
presidents.add(new President(id, firstName, lastName, height, weight, dateOfBirth));
} catch(IndexOutOfBoundsException | NumberFormatException | DateTimeParseException e) {
// Skip the line if it is missing a field, or if the String cannot be converted into an int, double, or LocalDate.
continue;
}
}
}
}
public class Main {
public static void notUsingLambdas() {
List<Book> books = Books.all();
Collections.sort(books);
for(Book book: books) {
System.out.println(book);
}
}
public static void main(String[] args) {
notUsingLambdas();
}
}
public class Main {
public static void usingLambdasLong() {
List<Book> books = Books.all();
Collections.sort(books, (Book b1, Book b2) -> {
return b1.getTitle().compareTo(b2.getTitle());
});
for(Book book: books) {
System.out.println(book);
}
}
public static void main(String[] args) {
usingLambdasLong();
}
}
public class Main {
public static void usingLambdasShort() {
List<Book> books = Books.all();
Collections.sort(books, (b1, b2) -> b1.getTitle().compareTo(b2.getTitle()));
for(Book book: books) {
System.out.println(book);
}
}
public static void main(String[] args) {
usingLambdasShort();
}
}
public class Main {
public static void usingLambdasShort() {
List<Book> books = Books.all();
Collections.sort(books, (b1, b2) -> b1.getTitle().compareTo(b2.getTitle()));
books.forEach(book -> System.out.println(book));
}
public static void main(String[] args) {
usingLambdasShort();
}
}
public class Main {
public static void usingMethodReferences() {
List<Book> books = Books.all();
// Collections.sort(books, Comparator.comparing(b -> b.getTitle()));
Collections.sort(books, Comparator.comparing(Book::getTitle));
books.forEach(System.out::println);
}
public static void main(String[] args) {
usingMethodReferences();
List<String> names = new ArrayList<>();
names.add("Marc");
names.add("amy");
Collections.sort(names, String::compareToIgnoreCase);
names.forEach(name -> {
name = name.toUpperCase();
System.out.printf("Hello %s\n", name);
});
}
}
import java.util.*;
class SortVehiclesByNumWheels implements Comparator<Vehicle> {
public int compare(Vehicle a, Vehicle b) {
int result = a.getNumWheels() - b.getNumWheels();
if(result == 0) {
SortVehiclesByName sortBy = new SortVehiclesByName();
result = sortBy.compare(a, b);
}
return result;
}
}
class SortVehiclesByMpg implements Comparator<Vehicle> {
public int compare(Vehicle a, Vehicle b) {
int result = 0;
if (a.getMpg() < b.getMpg()) result = -1;
if (a.getMpg() > b.getMpg()) result = 1;
if(result == 0) {
SortVehiclesByName sortBy = new SortVehiclesByName();
result = sortBy.compare(a, b);
}
return result;
}
}
class SortVehiclesByName implements Comparator<Vehicle> {
public int compare(Vehicle a, Vehicle b) {
int result = a.getMake().compareToIgnoreCase(b.getMake());
if(result == 0) {
result = a.getModel().compareToIgnoreCase(b.getModel());
}
return result;
}
}
class Vehicle implements Comparable<Vehicle> {
private String make;
private String model;
private double mpg;
private int numWheels;
public Vehicle(String make, String model, double mpg, int numWheels) {
this.make = make;
this.model = model;
this.mpg = mpg;
this.numWheels = numWheels;
}
public String getMake() {
return make;
}
public String getModel() {
return model;
}
public double getMpg() {
return mpg;
}
public int getNumWheels() {
return numWheels;
}
public String toString() {
return "Make: " + make + ", Model: " + model + ", MPG: " + mpg + ", Num Wheels: " + numWheels;
}
public int compareTo(Vehicle other) {
SortVehiclesByName sortBy = new SortVehiclesByName();
int result = sortBy.compare(this, other);
return result;
}
}
public class MyClass {
public static void main(String args[]) {
Vehicle v1 = new Vehicle("Ford", "F-150", 12.8, 4);
Vehicle v2 = new Vehicle("Chevrolet", "Corvette", 12.8, 4);
Vehicle v3 = new Vehicle("Ford", "Mustang", 20.2, 4);
Vehicle v4 = new Vehicle("Chevrolet", "Camaro", 19.5, 4);
Vehicle v5 = new Vehicle("Harley Davidson", "Iron 883", 51, 2);
List<Vehicle> vehicles = new ArrayList<>();
vehicles.add(v1);
vehicles.add(v2);
vehicles.add(v3);
vehicles.add(v4);
vehicles.add(v5);
System.out.println("Show vehicles left to right");
printCars(vehicles);
System.out.println("Show vehicles alphabetically");
Collections.sort(vehicles);
printCars(vehicles);
System.out.println("Show vehicles by MPG");
Collections.sort(vehicles, new SortVehiclesByMpg());
printCars(vehicles);
System.out.println("Show vehicles by number of wheels");
Collections.sort(vehicles, new SortVehiclesByNumWheels());
printCars(vehicles);
}
public static void printCars(List<Vehicle> vehicles) {
for(int i = 0; i < vehicles.size(); i++) {
System.out.println((i+1) + ") " + vehicles.get(i));
}
System.out.println();
}
}
import java.util.*;
class CompareClass implements Comparator<Vehicle> {
public int compare(Vehicle a, Vehicle b) {
int result = a.getClass().getName().compareTo(b.getClass().getName());
return result;
}
}
class SortVehiclesByNumWheels implements Comparator<Vehicle> {
public int compare(Vehicle a, Vehicle b) {
int result = a.getNumWheels() - b.getNumWheels();
if(result == 0) {
SortVehiclesByName sortBy = new SortVehiclesByName();
result = sortBy.compare(a, b);
}
return result;
}
}
class SortVehiclesByMpg implements Comparator<Vehicle> {
public int compare(Vehicle a, Vehicle b) {
int result = 0;
if (a.getMpg() < b.getMpg()) result = -1;
if (a.getMpg() > b.getMpg()) result = 1;
if(result == 0) {
SortVehiclesByName sortBy = new SortVehiclesByName();
result = sortBy.compare(a, b);
}
return result;
}
}
class SortVehiclesByName implements Comparator<Vehicle> {
public int compare(Vehicle a, Vehicle b) {
int result = a.getMake().compareToIgnoreCase(b.getMake());
if(result == 0) {
result = a.getModel().compareToIgnoreCase(b.getModel());
}
return result;
}
}
class Car extends Vehicle {
public Car(String make, String model, double mpg, int numWheels) {
super(make, model, mpg, numWheels);
}
}
class Truck extends Vehicle {
public Truck(String make, String model, double mpg, int numWheels) {
super(make, model, mpg, numWheels);
}
}
class Motorcycle extends Vehicle {
public Motorcycle(String make, String model, double mpg, int numWheels) {
super(make, model, mpg, numWheels);
}
}
class Vehicle implements Comparable<Vehicle> {
private String make;
private String model;
private double mpg;
private int numWheels;
public Vehicle(String make, String model, double mpg, int numWheels) {
this.make = make;
this.model = model;
this.mpg = mpg;
this.numWheels = numWheels;
}
public String getMake() {
return make;
}
public String getModel() {
return model;
}
public double getMpg() {
return mpg;
}
public int getNumWheels() {
return numWheels;
}
public String toString() {
return "Make: " + make + ", Model: " + model + ", MPG: " + mpg + ", Num Wheels: " + numWheels;
}
public int compareTo(Vehicle other) {
SortVehiclesByName sortBy = new SortVehiclesByName();
int result = sortBy.compare(this, other);
return result;
}
}
public class MyClass {
public static void main(String args[]) {
Vehicle v1 = new Truck("Ford", "F-150", 12.8, 4);
Vehicle v2 = new Car("Chevrolet", "Corvette", 12.8, 4);
Vehicle v3 = new Car("Ford", "Mustang", 20.2, 4);
Vehicle v4 = new Car("Chevrolet", "Camaro", 19.5, 4);
Vehicle v5 = new Motorcycle("Harley Davidson", "Iron 883", 51, 2);
List<Vehicle> vehicles = new ArrayList<>();
vehicles.add(v1);
vehicles.add(v2);
vehicles.add(v3);
vehicles.add(v4);
vehicles.add(v5);
System.out.println("Show vehicles left to right");
printCars(vehicles);
System.out.println("Show vehicles alphabetically");
Collections.sort(vehicles);
printCars(vehicles);
System.out.println("Show vehicles by MPG");
Collections.sort(vehicles, new SortVehiclesByMpg());
printCars(vehicles);
System.out.println("Show vehicles by number of wheels");
Collections.sort(vehicles, new SortVehiclesByNumWheels());
printCars(vehicles);
System.out.println("Show cars, then motorcycles, then trucks");
Collections.sort(vehicles, new CompareClass());
printCars(vehicles);
}
public static void printCars(List<Vehicle> vehicles) {
for(int i = 0; i < vehicles.size(); i++) {
System.out.println((i+1) + ") " + vehicles.get(i));
}
System.out.println();
}
}
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.Map;
import java.util.Comparator;
class Book implements Comparable<Book>{
private String title;
private LocalDate dateAdded;
public Book (String title, LocalDate dateAdded) {
this.title = title;
this.dateAdded = dateAdded;
}
public String getTitle() {
return title;
}
public LocalDate getDateAdded() {
return dateAdded;
}
public String toString() {
return title + " was added on " + dateAdded;
}
public int compareTo (Book other) {
// return this.title.compareTo(other.title);
return dateAdded.compareTo(other.dateAdded);
}
}
public class MyClass {
public static void main(String args[]) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
Book b1 = new Book ("Book1", LocalDate.parse("2005-11-12", formatter));
Book b2 = new Book ("Book2", LocalDate.parse("2006-09-19", formatter));
Book b3 = new Book ("Book3", LocalDate.parse("2004-04-23", formatter));
SortedSet<Book> books = new TreeSet<>();
books.add(b1);
books.add(b2);
books.add(b3);
System.out.println("*** Printing books in a SortedSet ***");
for(Book b: books) {
System.out.println(b);
}
System.out.println(books);
System.out.println();
SortedMap<Integer, Book> books2 = new TreeMap<>();
books2.put(1, b1);
books2.put(2, b2);
books2.put(3, b3);
System.out.println("*** Printing books in a SortedMap ***");
for(Map.Entry<Integer, Book> entry : books2.entrySet()) {
Integer key = entry.getKey();
Book value = entry.getValue();
System.out.println(key + " - " + value);
}
System.out.println(books2);
System.out.println(entriesSortedByValues(books2));
}
// Code from https://stackoverflow.com/questions/2864840/treemap-sort-by-value
static <K,V extends Comparable<? super V>> SortedSet<Map.Entry<K,V>> entriesSortedByValues(Map<K,V> map) {
SortedSet<Map.Entry<K,V>> sortedEntries = new TreeSet<Map.Entry<K,V>>(
new Comparator<Map.Entry<K,V>>() {
@Override public int compare(Map.Entry<K,V> e1, Map.Entry<K,V> e2) {
int res = e1.getValue().compareTo(e2.getValue());
return res != 0 ? res : 1;
}
}
);
sortedEntries.addAll(map.entrySet());
return sortedEntries;
}
}
git remote -v
git remote add upstream https://github.com/mlhaus/xxxx.git
git remote -v
git checkout -b yourname-contribution1
git add .
git commit -m 'A meaningful message'
git push origin yourname-contribution1
git checkout main
git pull origin main
Contributors only:
Note: If you made any changes to the main branch (which you shouldn't have), you must remove or commit the code before continuing.
Use the Git > Fetch command to obtain the change history (branches and commits) from the upstream repo.
Or you can enter this command:
git fetch upstream
When you fetch changes from upstream, all new commits are downloaded and stored as a remote branch.
Contributors only:
Use the Git > Merge command to merge changes from the upstream main branch into your local main branch.
git merge upstream/main
git push origin main
Original
Repo
Your
Copy
Local Computer
Fork it
Clone to
set Origin
Set Upstream
Fetch
Changes
Push Changes
During the month of October, there is a global open source contribution initiative called Hacktoberfest.
To participate, you need to register your GitHub account on their website and make at least 4 meaningful pull requests in the month of October.
Here are some examples of open source projects
By Marc Hauschildt
Web Technologies and Computer Software Development Instructor at Kirkwood Community College in Cedar Rapids, IA.