--Introduction --Créer un collectionneur -Facile à utiliser Collector
--Depuis Java 8, l'API Stream est largement utilisée au lieu de l'instruction for --Stream dispose d'un ensemble de traitements de terminaison, dont le représentant est la méthode de collecte.
java.util.stream.Collector//Collecteur à convertir en ArrayList
Collector<T, ?, List<T>> toArrayList = Collector.of(
        ArrayList::new,
        List::add,
        (l1, l2) -> {
            l1.addAll(l2);
            return l1;
        },
        Characteristics.IDENTITY_FINISH);
//Courir
.stream().collect(toArrayList);
Il existe de nombreux articles d'introduction sur la façon de procéder, alors allez-y.
//Exemple de méthode
Stream<String> stream() {
  return Stream.of("1","20","30");
}
//Convertir en liste: [1, 20, 30]
stream().collect(toList());
//Concaténation de chaînes: "<1,20,30>"
stream().collect(joining(",", "<", ">"));
//regroupement: {1=[1], 2=[20, 30]}
stream().collect(groupingBy(String::length));
//Liste qui ne peut pas être modifiée
stream().collect(collectingAndThen(toList(), Collections::unmodifiableList));
Utilisateur A: Collector ne fait pas grand chose Utilisateur B: il est difficile d'appeler les collectionneurs à chaque fois Utilisateur C: Je veux que Stream ait toList ou toMap directement comme les autres langues.
C'est vrai, mais collect est une méthode légèrement plus générique
class Hoge {
	String methodA(String str) {
		if (str == null || str.equals("")) {
			return "A";
		}
		// ..
	}
	String methodB(String str) {
		if (str == null || str.equals("")) {
			return "B";
		}
		// ..
	}
}
class StringUtil {
	boolean isEmpty(String str) {
		return str == null || str.equals("");
	}
}
class Hoge {
	String methodA(String str) {
		if (isEmpty(str)) {
			return "A";
		}
		// ..
	}
	String methodB(String str) {
		if (isEmpty(str)) {
			return "B";
		}
		// ..
	}
}
String methodA(List<String> list) {
  list.stream()
    .map(/* ... */)
    .collect(collectingAndThen(toList(),Collections::unmodifiableList));
}
 
String methodB(List<String> list) {
  list.stream()
    .filter(/* ... */)
    .collect(collectingAndThen(toList(),Collections::unmodifiableList));
}
//Classe d'utilité du collecteur
class Collectors2 {
    //Renvoie un collecteur qui se convertit en une liste non modifiable
  static <T> Collector<T,?,List<T>> toUnmodifiableList() {
    return collectingAndThen(toList(), Collections::unmodifiableList);
  }
}
//Utiliser l'utilitaire
stream()
    .collect(collectingAndThen(toList(),Collections::unmodifiableList));
// ↓
stream()
    .collect(toUnmodifiableList());
Cependant, il faut tenir compte de la compréhensibilité
class Collectors2 {
  //Groupe et carte.Collecteur qui renvoie Stream of Entity
  static <T, K> Collector<T, ?, Stream<Map.Entry<K, List<T>>>> grouping(Function<T, K> mapper) {
    return collectingAndThen(
                groupingBy(mapper),
                m -> m.entrySet().stream()
        );
  }
}
//Regrouper et convertir à nouveau en Stream
stream()
    .collect(groupingBy(String::length)).entrySet().stream();
// ↓
stream()
    .collect(grouping(String::length));
//Classe avec historique des événements
@AllArgsConstructor
class History {
    List<String> events;
}
//Faites une liste d'événements
List<String> events = stream().collect(toList());
//Générer l'historique
History history = new History(events);
List<String> events = stream().collect(toList());
History history = new History(events);
// ↓
//Convertir directement en historique
History history = stream()
    .collect(collectingAndThen(toList(), History::new));
class Collectors2 {
  //Après la conversion en List, retournez Collector qui exécute la fonction de mappage
    static <T, R> Collector<T, ?, R> toListAnd(Function<List<T>, R> mapper) {
    return collectingAndThen(toList(), mapper);
    }
}
//appel
History history = stream()
  .collect(collectingAndThen(toList(), History::new));
// ↓
History history = stream()
  .collect(toListAnd(History::new));
class Collectors2 {
  // toList()Facultatif si est vide.empty(), Facultatif si non vide<List<T>>rends le
  static <T> Collector<T, ?, Optional<List<T>>> toOptionalList() {
    return collectingAndThen(toList(), l -> l.isEmpty() ? Optional.empty() : Optional.of(l));
  }
  //Exécuter la fonction avec cette liste comme argument uniquement lorsque la liste n'est pas vide
  static <T, R> Collector<T, ?, Optional<R>> ifNotEmptyList(Function<List<T>, R> mapper) {
    return collectingAndThen(toOptionalList(), op -> op.map(mapper));
  }
}
//Générer l'historique uniquement lorsque la liste n'est pas vide
Optional<History> history = stream()
    .collect(ifNotEmptyList(History::new));
//Convertir en Json
stream
    .collect(toJson());
//Convertir en CSV
stream
    .collect(toCsv());
//Convertir en paramètres de demande
stream
    .collect(toRequestParam());
//Convertir en SQL
stream
    .collect(toSql());
Enjoy collecting!!
http://www.ne.jp/asahi/hishidama/home/tech/java/collector.html
Recommended Posts