Skip to content

Instantly share code, notes, and snippets.

@bastienapp
Created January 21, 2019 12:50
Show Gist options
  • Save bastienapp/8d35871a975ac8c9c8e65e2fe32550cc to your computer and use it in GitHub Desktop.
Save bastienapp/8d35871a975ac8c9c8e65e2fe32550cc to your computer and use it in GitHub Desktop.
Version de Generics sans lambdas
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
public class Generics {
interface Predicate<T> {
boolean filter(T obj);
}
interface Mapper<T, U> {
U map(T obj);
}
/**
* Java entry point
*/
public static void main(String... args) {
new Generics();
}
/**
* Class Constructor
*/
private Generics() {
List<Integer> ints = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
List<String> strs = Arrays.asList("tout", "titi", "ototo", "jean", "tous", "taratata");
// TODO - Ne retourner que les nombres pairs.
ints = filter(ints, new Predicate<Integer>() {
@Override
public boolean filter(Integer i) {
return false;
}
});
// TODO - Multiplier par 2 chaque élément de la liste.
ints = map(ints, new Mapper<Integer, Integer>() {
@Override
public Integer map(Integer i) {
return null;
}
});
for (Integer i : ints) System.out.println(i);
// TODO - Ne retourner que les Strings contenant au moins 2 lettres t.
//strs = ...
// TODO - Passer en majuscule toutes les Strings
//strs = ...
for (String s : strs) System.out.println(s);
}
/**
* Returns a list consisting of the elements of a collection that match the given predicate.
*
* @param c Collection<T>: The input collection
* @param p The predicate
* @param <T> Type of the element in the collection
* @return A list that match the given filter.
*/
private <T> List<T> filter(Collection<T> c, Predicate<T> p) {
List<T> result = new ArrayList<>();
// TODO - Ajouter le code ici
// Retourner 'result' contenant les éléments de Collection filtrés par la méthode o.filter().
return result;
}
/**
* Returns a list consisting of the results of applying the given function to the elements of the collection.
*
* @param c Collection<T>: The input collection
* @param m The predicate
* @param <T> Type of the element in the collection
* @param <U> Type of the element in the returned list
* @return A list that match the given mapper.
*/
private <T, U> List<U> map(Collection<T> c, Mapper<T, U> m) {
List<U> result = new ArrayList<>();
// TODO - Ajouter le code ici
// Retourner 'result' contenant les éléments de la Collection modifiés par la méthode m.map().
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment