--Introduction --Create a Collector --Easy to use Collector --Collect Collectors --Generate from Collector
--Since Java 8 Stream API is widely used instead of for statement
--Stream has a set of termination processing, the representative of which is the collect method.
--The argument of the collect method is java.util.stream.Collector
//Collector to convert to ArrayList
Collector<T, ?, List<T>> toArrayList = Collector.of(
        ArrayList::new,
        List::add,
        (l1, l2) -> {
            l1.addAll(l2);
            return l1;
        },
        Characteristics.IDENTITY_FINISH);
//Run
.stream().collect(toArrayList);
There are many introductory articles on how to do this, so go there.
//Sample method
Stream<String> stream() {
  return Stream.of("1","20","30");
}
//Convert to List: [1, 20, 30]
stream().collect(toList());
//String concatenation: "<1,20,30>"
stream().collect(joining(",", "<", ">"));
//grouping: {1=[1], 2=[20, 30]}
stream().collect(groupingBy(String::length));
//List that cannot be changed
stream().collect(collectingAndThen(toList(), Collections::unmodifiableList));
User A: Collector doesn't make that much User B: It's hard to call Collectors every time User C: I want Stream to have toList or toMap directly like other languages.
That's true, but collect is a slightly more generic method.
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));
}
//Collector utility class
class Collectors2 {
    //Returns a Collector that converts to an Unmodifiable List
  static <T> Collector<T,?,List<T>> toUnmodifiableList() {
    return collectingAndThen(toList(), Collections::unmodifiableList);
  }
}
//Use utility
stream()
    .collect(collectingAndThen(toList(),Collections::unmodifiableList));
// ↓
stream()
    .collect(toUnmodifiableList());
However, consideration must be given to comprehensibility
class Collectors2 {
  //Group and Map.Collector that returns 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()
        );
  }
}
//Group and convert to Stream again
stream()
    .collect(groupingBy(String::length)).entrySet().stream();
// ↓
stream()
    .collect(grouping(String::length));
//Class with event history
@AllArgsConstructor
class History {
    List<String> events;
}
//Make a list of events
List<String> events = stream().collect(toList());
//Generate History
History history = new History(events);
List<String> events = stream().collect(toList());
History history = new History(events);
// ↓
//Convert directly to History
History history = stream()
    .collect(collectingAndThen(toList(), History::new));
class Collectors2 {
  //After converting to List, return Collector that executes mapper function
    static <T, R> Collector<T, ?, R> toListAnd(Function<List<T>, R> mapper) {
    return collectingAndThen(toList(), mapper);
    }
}
//call
History history = stream()
  .collect(collectingAndThen(toList(), History::new));
// ↓
History history = stream()
  .collect(toListAnd(History::new));
class Collectors2 {
  // toList()Optional if is empty.empty(), Optional if not empty<List<T>>return it
  static <T> Collector<T, ?, Optional<List<T>>> toOptionalList() {
    return collectingAndThen(toList(), l -> l.isEmpty() ? Optional.empty() : Optional.of(l));
  }
  //Execute the function with the list as an argument only when the List is not empty
  static <T, R> Collector<T, ?, Optional<R>> ifNotEmptyList(Function<List<T>, R> mapper) {
    return collectingAndThen(toOptionalList(), op -> op.map(mapper));
  }
}
//Generate History only when List is not empty
Optional<History> history = stream()
    .collect(ifNotEmptyList(History::new));
//Convert to Json
stream
    .collect(toJson());
//Convert to CSV
stream
    .collect(toCsv());
//Convert to request parameter
stream
    .collect(toRequestParam());
//Convert to SQL
stream
    .collect(toSql());
-Synthesize Java8 Stream API Collector -How to use a certain Doma2
--Java 8 and later Stream is a frequent API --Collector is a part of where Stream is --The collect method is generic --Collectors can be combined and shared --Collector can be converted to your favorite object depending on how you use it
Enjoy collecting!!
http://www.ne.jp/asahi/hishidama/home/tech/java/collector.html
Recommended Posts