Compare a Collection of Objects using Java 7 Vs Java 8 ?

Here in this example we will see, how we can compare a list of objects to find a particular one based on some condition. Consider the following example. Here we are going to find the costliest iPhone from a list of  iPhones.

For this example we are using the following class to create Object of different models of iPhone.

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

// We are not considering the standard naming convention of classes here
// as its a iPhone
class iPhone {
  private String color;
  private String version;
  private int price;

  public iPhone(String color, String version, int price) {
	super();
	this.color = color;
	this.version = version;
	this.price = price;
  }

  public int getPrice() {
	return price;
  }

  @Override
  public String toString() {
	return "IPhone [color=" + color + ", version=" + version + ", price="
			+ price + "]";
  }
}

Now in the PricingManager class we are finding the costliest iPhone from a collection, using Java 7 and Java 8.

public class PricingManager {

  private static iPhone getCostliestIPhoneJava7(List list) {
	iPhone costliestPhone = new iPhone("", "", 0);
	for (iPhone iphone : list) {
		if (iphone.getPrice() > costliestPhone.getPrice()) {
			costliestPhone = iphone;
		}
	}
	return costliestPhone;
  }

  private static iPhone getCostliestIPhoneJava8(List list) {
	return list.stream() // Convert collection to Stream
			.max(Comparator.comparing(iPhone::getPrice)) // Compares people ages
			.get(); // Gets stream result
  }

  public static void main(String[] args){
	iPhone iPhone1 = new iPhone("White", "5S", 16000);
	iPhone iPhone2 = new iPhone("Golden", "6S", 42000);
	iPhone iPhone3 = new iPhone("White", "7", 62000);

	List phoneList = Arrays.asList(iPhone1,iPhone2,iPhone3);

	System.out.println("Get costliest iPhone by Java 7");
	System.out.println(getCostliestIPhoneJava7(phoneList));
	System.out.println("--------------------------------");
	System.out.println("Get costliest iPhone by Java 8");
	System.out.println(getCostliestIPhoneJava8(phoneList));
  }
}

 

Java-8 12 Stream 12

FOLLOW US ON LinkedIn



Explore Tutu'rself