Created
May 15, 2015 15:25
-
-
Save knight1128/fbb711b1dd8eea38dd60 to your computer and use it in GitHub Desktop.
java 8 lamda sort vs java 7 sort
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.google.locationlab; | |
import com.google.common.collect.Lists; | |
import com.google.common.collect.Ordering; | |
import com.google.common.primitives.Ints; | |
import org.apache.commons.lang.builder.ToStringBuilder; | |
import org.apache.commons.lang.builder.ToStringStyle; | |
import org.junit.Before; | |
import org.junit.Test; | |
import java.util.Collections; | |
import java.util.Comparator; | |
import java.util.List; | |
public class Java8Test { | |
private static List<Person> persons; | |
@Before | |
public void before() { | |
persons = Lists.newArrayList(); | |
persons.add(new Person(1, "Samuel", 30)); | |
persons.add(new Person(2, "Jason", 25)); | |
persons.add(new Person(3, "Brian", 55)); | |
persons.add(new Person(4, "Cato", 32)); | |
//System.out.println(persons); | |
} | |
// java.util.Collection sorting | |
@Test | |
public void java7CollectionSortTest() { | |
Collections.sort(persons, new Comparator<Person>() { | |
public int compare(Person p1, Person p2) { | |
return p1.age.compareTo(p2.age); | |
} | |
}); | |
System.out.println("java7CollectionSortTest : " + persons); | |
} | |
@Test | |
public void java7GuavaCollectionSortTest() { | |
Collections.sort(persons, new Ordering<Person>() { | |
@Override | |
public int compare(Person p1, Person p2) { | |
return Ints.compare(p1.age, p2.age); | |
} | |
}); | |
System.out.println("java7GuavaCollectionSortTest : " + persons); | |
} | |
@Test | |
public void java8LamdaWithTypeCollectionSortTest() { | |
Collections.sort(persons, (Person p1, Person p2) -> Ints.compare(p1.age, p2.age)); | |
System.out.println("java8LamdaWithTypeCollectionSortTest : " + persons); | |
} | |
@Test | |
public void java8LamdaWithoutTypeCollectionSortTest() { | |
Collections.sort(persons, (p1, p2) -> Ints.compare(p1.age, p2.age)); | |
System.out.println("java8LamdaWithoutTypeCollectionSortTest : " + persons); | |
} | |
@Test | |
public void java8LamdaSort() { | |
persons.sort((p1, p2) -> p1.age.compareTo(p2.age)); | |
System.out.println("java8LamdaSort : " + persons); | |
} | |
} | |
class Person { | |
Integer id; | |
String name; | |
Integer age; | |
public Person(int id, String name, int age) { | |
this.id = id; | |
this.name = name; | |
this.age = age; | |
} | |
@Override | |
public String toString() { | |
return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE); | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
result