Skip to content

Instantly share code, notes, and snippets.

@fupfin
Last active August 29, 2015 14:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fupfin/3ca333ff9bb36f9a976d to your computer and use it in GitHub Desktop.
Save fupfin/3ca333ff9bb36f9a976d to your computer and use it in GitHub Desktop.
Schwartz Transform Java 8 Version
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());
}
}
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