Last active
August 29, 2015 14:12
-
-
Save fupfin/3ca333ff9bb36f9a976d to your computer and use it in GitHub Desktop.
Schwartz Transform Java 8 Version
This file contains 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
import java.util.List; | |
import java.util.function.Function; | |
import java.util.stream.Collectors; | |
import org.javatuples.*; | |
public class Schwartz { | |
public static <T> List<T> transform(List<T> list, Function<T, Integer>fn) { | |
return list.stream() | |
.map(x -> Pair.with(x, fn.apply(x))) | |
.sorted((a, b) -> a.getValue1() - b.getValue1()) | |
.map(p -> p.getValue0()) | |
.collect(Collectors.toList()); | |
} | |
} |
This file contains 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
import static org.junit.Assert.*; | |
import static org.hamcrest.CoreMatchers.*; | |
import java.util.*; | |
import org.junit.Test; | |
public class SchwartzTest { | |
@Test | |
public void test() { | |
List<String> result = Schwartz.transform(Arrays.asList("abc", "a", "cc", "abcdefg"), s -> s.length()); | |
assertThat(result.get(0), is("a")); | |
assertThat(result.get(3), is("abcdefg")); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment