Stream Gatherers عمليًا، الجزء 1
الخطوة الأولى في رحلتنا مع Stream Gatherers، وهي ميزة جديدة لافتة في Java 22، مع التركيز على بناء Gatherers مخصصة تحل مشكلات واقعية.
يحمل Java 22 ميزة معاينة لافتة هي JEP 461: Stream Gatherers، وهي ترقية أساسية لواجهة Stream API. وفي صميمها دالة gather جديدة تجعل الواجهة أكثر قابلية للتخصيص ومرونة وكفاءة. وأهدافها:
- جعل Stream API أكثر تكيفًا، بما يتيح عمليات على التدفقات تناسب احتياجات محددة بصورة أفضل.
- تحسين إمكانية إعادة استخدام الشيفرة في المهام القائمة على التدفقات.
- جعل عمليات التدفقات المعقدة أسهل فهمًا وتنفيذًا.
والأهم أن كل هذا يتحقق دون زيادة تعقيد Stream API الحالية كثيرًا.
يأتي هذا الاستكشاف في جزأين: تتناول هذه المقالة المفاهيم الأساسية لـ Gatherers وكيفية تطبيقها في عمليات عملية. وسينظر الجزء التالي في gatherers المدمجة وكيفية دمجها في عمليات معقدة.
فهم واجهة Gatherer
تقع واجهة Gatherer في صميم JEP 461 وتتيح تخصيص عمليات التدفقات في Java 22. وتتكون من بضع دوال أساسية تدعم معالجة البيانات المعقدة بطريقة مبسطة وفعالة:
- دالة Initializer: اختيارية، وتكتسب أهمية خاصة عندما يستخدم المُدمِج (integrator) أو المُنهي (finisher) حالة داخلية. وفي هذه الحالة تتولى دالة Initializer تهيئة هذه الحالة الداخلية بشكل صحيح قبل معالجة أي بيانات.
- دالة Integrator: يجب تنفيذها دائمًا. وهي الدالة المركزية التي تعرّف منطق معالجة البيانات الفعلي. يحتاجها كل Gatherer ليحدد كيف يُعالَج كل عنصر من التدفق ويُدمج في الحالة الحالية.
- دالة Finisher: تنفيذها اختياري. وهي تتولى المعالجة النهائية والتحويلات بعد دمج جميع العناصر.
- دالة Combiner: إعادة تعريفها اختيارية. وهذه الدالة أساسية لعمليات التدفقات المتوازية، إذ تحدد كيفية دمج النتائج من أجزاء التدفق المختلفة. وتهم عندما يُعالَج التدفق على التوازي، ويجب تكييفها مع احتياجات المعالجة المتوازية الخاصة بك.
- دالة AndThen: إعادة تعريفها اختيارية. ويتيح التنفيذ الافتراضي بناء gatherer من gatherers أخرى.
تعمل الدالة Stream::gather جنبًا إلى جنب مع واجهة Gatherer، مما يتيح طريقة أكثر تعبيرًا ومرونة لمعالجة التدفقات. فبتمرير نسخة من Gatherer إلى Stream::gather يستطيع المطورون بناء عمليات مخصصة تناسب احتياجاتهم الخاصة، متجاوزين حدود العمليات المعرَّفة مسبقًا في Stream API.
تنفيذ Gatherers مخصصة
في هذا القسم سننظر في كيفية استخدام دالة gather المضافة إلى Stream API في Java 22 عمليًا. ولإظهار مدى تنوعها وقوتها سنبني عدة gatherers مخصصة تعمل على فئة Money مصممة لهذا الغرض. ستوضح هذه الأمثلة كيف تستطيع دالة gather تبسيط العمليات على أنواع البيانات المعقدة وتحسينها، مسلطة الضوء على القيمة العملية والإمكانات المبتكرة لهذه الميزة الجديدة معًا. وكما ذُكر سابقًا، لا تزال Stream Gatherers في مرحلة المعاينة، لذا يجب تفعيل الوظيفة بعلم JVM –enable-preview.
public record Money(BigDecimal amount, Currency currency) {
public Money add(Money money) {
return new Money(money.amount.add(this.amount), currency);
}
public Money multiply(BigDecimal multiplier) {
return new Money(amount.multiply(multiplier), currency);
}
}
Distinct by Gatherer
لإظهار فائدة دالة gather، لنبدأ بـ DistinctByGatherer. وهو يُبقي عناصر التدفق فريدة وفق دالة محدِّدة (selector) – وهو أمر لا يدعمه Stream API جاهزًا.
public class DistinctByGatherer<T, P> implements Gatherer<T, Set<P>, T> {
private final Function<T, P> selector;
public DistinctByGatherer(Function<T, P> selector) {
this.selector = selector;
}
@Override
public Supplier<Set<P>> initializer() {
return HashSet::new;
}
@Override
public Integrator<Set<P>, T, T> integrator() {
return Integrator.ofGreedy((state, item, downstream) -> {
P extracted = selector.apply(item);
if(!state.contains(extracted)) {
state.add(extracted);
downstream.push(item);
}
return true;
});
}
}
هنا يعتمد DistinctByGatherer على:
- مُهيِّئ (initializer) يعدّ الحالة الداخلية – أي مجموعة (set) تتتبع العناصر التي سبق رؤيتها.
- مُدمِج (integrator) يضمن فرادة العناصر وفق الدالة المحدِّدة المعطاة. ويعمل مع:
- state: يحمل المجموعة الداخلية، التي أنشأتها الدالة initializer()، وتُستخدم لتتبع العناصر الفريدة.
- item: عنصر تدفق الإدخال الذي تجري معالجته حاليًا.
- downstream: المرحلة التالية من خط المعالجة، التي تتلقى العنصر إذا اجتاز فحص الفرادة.
ولتسهيل الاستخدام نضيف فئة مصنع (factory) هي MyGatherers:
public class MyGatherers {
public static <T, P> DistinctByGatherer<T, P> distinctBy(Function<T, P> extractor) {
return new DistinctByGatherer<>(extractor);
}
}
تطبيق هذا الـ gatherer على الفئة Money:
var money = List.of(
new Money(BigDecimal.valueOf(12), PLN),
new Money(BigDecimal.valueOf(11), EUR),
new Money(BigDecimal.valueOf(15), PLN)
);
System.out.println("\nDistinct By Currency:");
money.stream()
.gather(MyGatherers.distinctBy(Money::currency))
.forEach(System.out::println);
المخرجات:
Distinct By Currency:
Money[amount=12, currency=PLN]
Money[amount=11, currency=EUR]
يمثل DistinctByGatherer امتدادًا مصقولًا للدالة القياسية Stream::distinct، إذ يوفر مرونة أكبر وتصفية أغنى استنادًا إلى معايير مخصصة بدلًا من مجرد مساواة الكائنات.
Reduce by Gatherer
لننظر الآن في ReduceByGatherer، الذي يجمّع عناصر التدفق وفق دالة محدِّدة. وعلى عكس DistinctByGatherer فهو لا يتخطى المكررات بل يدمج العناصر التي تظهر أكثر من مرة.
public class ReduceByGatherer<T, P> implements Gatherer<T, Map<P, T>, T> {
private final Function<T, P> selector;
private final BiFunction<T, T, T> operation;
public ReduceByGatherer(Function<T, P> extractor, BiFunction<T, T, T> reducer) {
this.selector = extractor;
this.operation = reducer;
}
@Override
public Supplier<Map<P, T>> initializer() {
return HashMap::new;
}
@Override
public Integrator<Map<P, T>, T, T> integrator() {
return Integrator.ofGreedy((state, item, _) -> {
state.merge(selector.apply(item), item, operation);
return true;
});
}
@Override
public BiConsumer<Map<P, T>, Downstream<? super T>> finisher() {
return (state, downstream) -> state.values().forEach(downstream::push);
}
}
فيما يلي نسخة منقحة وأكثر شمولًا من القسم الذي يصف الجوانب الأساسية لـ ReduceByGatherer:
الجوانب الأساسية لـ ReduceByGatherer:
- إدارة الحالة: يستخدم HashMap لحفظ حالته، مما يتيح تجميع عناصر التدفق بفعالية.
- تنفيذ Integrator: يدمج العناصر أثناء معالجة التدفق، وفق الدالتين المحدِّدة والمختزِلة المعطاتين. وبدلًا من إرسال العناصر المعالجة مباشرة إلى المرحلة التالية كما في الأمثلة السابقة، تحتاج هذه الدالة إلى حفظها في HashMap لإدارة الحالة.
- تنفيذ Finisher: يكمل العملية بدفع القيم المتراكمة إلى المرحلة التالية بعد معالجة كل العناصر. وهذا ضروري لعمليات الاختزال، التي يجب فيها معالجة كل العناصر معًا قبل إنتاج نتيجة نهائية.
- معالجة التدفق كاملًا: على عكس العمليات التي تسمح بالإنهاء المبكر (مثل takeWhile)، يجب على ReduceByGatherer معالجة كل عناصر التدفق لإنتاج نتائج صحيحة.
إضافة ReduceByGatherer إلى فئة الأدوات المساعدة لدينا:
public class MyGatherers {
public static <T, P> DistinctByGatherer<T, P> distinctBy(Function<T, P> extractor) {
return new DistinctByGatherer<>(extractor);
}
public static <T, P> ReduceByGatherer<T, P> reduceBy(Function<T, P> extractor, BiFunction<T, T, T> reducer) {
return new ReduceByGatherer<>(extractor, reducer);
}
}
مثال على استخدام مع الفئة Money:
var money = List.of(
new Money(BigDecimal.valueOf(12), PLN),
new Money(BigDecimal.valueOf(11), EUR),
new Money(BigDecimal.valueOf(15), PLN)
);
System.out.println("Reduce By Currency");
money.stream()
.gather(MyGatherers.reduceBy(Money::currency, Money::add))
.forEach(System.out::println);
المخرجات:
Reduce By Currency
Money[amount=27, currency=PLN]
Money[amount=11, currency=EUR]
يدمج هذا الـ gatherer عناصر التدفق بكفاءة، مما يجعله مناسبًا جدًا لضغط البيانات أو تجميعها في تدفق منتهٍ.
Max by Gatherer
يجد MaxByGatherer أكبر عنصر في التدفق وفق دالة محدِّدة معطاة. وتنفيذه أكثر تعقيدًا، لأنه يضيف فئة منفصلة لإدارة الحالة ودالة combiner تحسّن دعمه لعمليات التدفقات المتوازية.
class MaxByGatherer<T, B extends Comparable<B>> implements Gatherer<T, State<T>, T> {
private final Function<T, B> extractor;
MaxByGatherer(Function<T, B> extractor) {
this.extractor = extractor;
}
@Override
public Supplier<State<T>> initializer() {
return State::new;
}
@Override
public Integrator<State<T>, T, T> integrator() {
return Integrator.ofGreedy((state, item, _) -> {
if (state.maxElement == null) {
state.maxElement = item;
return true;
}
B currentItemValue = extractor.apply(item);
B maxItemValue = extractor.apply(state.maxElement);
if (currentItemValue.compareTo(maxItemValue) > 0) {
state.maxElement = item;
}
return true;
});
}
@Override
public BinaryOperator<State<T>> combiner() {
return (first, second) -> {
if (first.maxElement == null && second.maxElement == null) {
return null;
} else if (first.maxElement == null) {
return second;
} else if (second.maxElement == null) {
return first;
}
B firstMaxValue = extractor.apply(first.maxElement);
B secondMaxValue = extractor.apply(second.maxElement);
if (firstMaxValue.compareTo(secondMaxValue) > 0) {
return first;
} else {
return second;
}
};
}
@Override
public BiConsumer<State<T>, Downstream<? super T>> finisher() {
return (state, downstream) -> downstream.push(state.maxElement);
}
}
class State<T> {
T maxElement;
}
الميزات الأساسية:
- إدارة الحالة: يتتبع أكبر عنصر بفئة State مخصصة.
- Integrator: يجد أكبر عنصر باستخدام دالة المقارنة المعطاة.
- Combiner: يدمج الحالة من أجزاء مختلفة، مما يجعل المعالجة في التدفقات المتوازية فعالة.
يوسّع هذا الـ gatherer كثيرًا قدرة Stream API على الحسابات المعقدة، مثل إيجاد القيم القصوى عند المعالجة على التوازي.
إضافة MaxByGatherer إلى MyGatherers:
public class MyGatherers {
public static <T, P> DistinctByGatherer<T, P> distinctBy(Function<T, P> extractor) {
return new DistinctByGatherer<>(extractor);
}
public static <T, P> ReduceByGatherer<T, P> reduceBy(Function<T, P> extractor, BiFunction<T, T, T> reducer) {
return new ReduceByGatherer<>(extractor, reducer);
}
public static <T, B extends Comparable<B>> MaxByGatherer<T, B> maxBy(Function<T, B> extractor) {
return new MaxByGatherer<>(extractor);
}
}
مثال على الاستخدام:
var money = List.of(
new Money(BigDecimal.valueOf(12), PLN),
new Money(BigDecimal.valueOf(11), PLN),
new Money(BigDecimal.valueOf(15), PLN)
);
System.out.println("\nMax By Amount");
money.stream()
.parallel()
.gather(MyGatherers.maxBy(Money::amount))
.forEach(System.out::println);
لاحظ أن تنفيذ combiner لا يدخل حيز العمل إلا عندما نستخدم تدفقًا متوازيًا.
المخرجات:
Max By Amount
Money[amount=15, currency=PLN]
يوضح هذا التنفيذ كيف يستطيع MaxByGatherer إيجاد القيمة القصوى في مجموعة بكفاءة.
Map Not-Null Gatherer
تخيّل أن لدينا قائمة من كائنات Money تتخللها قيم null. نريد إسقاط قيم null وتحويل العناصر المتبقية. يمكن فعل ذلك بدمج Stream::filter وStream::map، لكن لنجرب نهجًا أكثر انسيابية مستوحى من الدالة mapNotNull في Kotlin.
public class MapNotNullGatherer<T,M> implements Gatherer<T, T, M> {
private final Function<T, M> mapper;
public MapNotNullGatherer(Function<T, M> mapper) {
this.mapper = mapper;
}
@Override
public Integrator<T, T, M> integrator() {
return Integrator.ofGreedy((_, item, downstream) -> {
if(item != null) {
downstream.push(mapper.apply(item));
}
return true;
});
}
}
أبرز النقاط:
- البساطة: الدالة الوحيدة التي يحتاجها هذا الـ gatherer هي integrator، التي تُسقط قيم null وتطبّق دالة التحويل على العناصر غير الفارغة.
- الكفاءة: تحدث التصفية والتحويل في خطوة واحدة، مما يحسّن قابلية قراءة الشيفرة والأداء معًا.
إضافة MapNotNullGatherer إلى MyGatherers:
public class MyGatherers {
public static <T, P> DistinctByGatherer<T, P> distinctBy(Function<T, P> extractor) {
return new DistinctByGatherer<>(extractor);
}
public static <T, P> ReduceByGatherer<T, P> reduceBy(Function<T, P> extractor, BiFunction<T, T, T> reducer) {
return new ReduceByGatherer<>(extractor, reducer);
}
public static <T, B extends Comparable<B>> MaxByGatherer<T, B> maxBy(Function<T, B> extractor) {
return new MaxByGatherer<>(extractor);
}
public static <T, M> MapNotNullGatherer<T, M> mapNotNull(Function<T, M> mapper) {
return new MapNotNullGatherer<>(mapper);
}
}
مثال على الاستخدام:
var moneyWithNulls = Arrays.asList(
new Money(BigDecimal.valueOf(12), PLN),
null,
new Money(BigDecimal.valueOf(11), EUR),
new Money(BigDecimal.valueOf(15), PLN),
null
);
System.out.println("Map not-null Gatherer");
moneyWithNulls.stream()
.gather(MyGatherers.mapNotNull(m -> m.multiply(BigDecimal.TWO)))
.forEach(System.out::println);
المخرجات:
Map not-null Gatherer
Money[amount=24, currency=PLN]
Money[amount=22, currency=EUR]
Money[amount=30, currency=PLN]
يُظهر هذا التنفيذ كيف تستطيع gatherers المخصصة جعل عمليات التدفقات أبسط وأفضل، خاصة عندما تلزم التصفية والتحويل معًا.
Find first Gatherer
يمثل FindFirstGatherer صياغة مبتكرة للدالة القياسية Stream::findFirst تختلف عنها في أمرين أساسيين:
- مخرجات من نوع تدفق: بينما تعيد Stream::findFirst قيمة Optional<T>، ينتج هذا الـ gatherer تدفقًا Stream<T> – إما فارغًا أو يحتوي عنصرًا واحدًا، بحسب ما إذا تحقق الشرط (predicate).
- التصفية القائمة على شرط: يعمل بشرط، فيعالج العناصر انتقائيًا حتى يجد أول تطابق.
public class FindFirstGatherer<T> implements Gatherer<T, T, T> {
private final Predicate<T> predicate;
public FindFirstGatherer(Predicate<T> predicate) {
this.predicate = predicate;
}
@Override
public Integrator<T, T, T> integrator() {
return Integrator.ofGreedy((_, item, downstream) -> {
if (predicate.test(item)) {
downstream.push(item);
return false;
} else {
return true;
}
});
}
}
وبمجرد العثور على عنصر يحقق الشرط، يتوقف التنفيذ عن معالجة أي عناصر أخرى. وعندما يحدث ذلك تعيد integrator القيمة false.
إضافة FindFirstGatherer إلى MyGatherers:
public class MyGatherers {
public static <T, P> DistinctByGatherer<T, P> distinctBy(Function<T, P> extractor) {
return new DistinctByGatherer<>(extractor);
}
public static <T, P> ReduceByGatherer<T, P> reduceBy(Function<T, P> extractor, BiFunction<T, T, T> reducer) {
return new ReduceByGatherer<>(extractor, reducer);
}
public static <T, B extends Comparable<B>> MaxByGatherer<T, B> maxBy(Function<T, B> extractor) {
return new MaxByGatherer<>(extractor);
}
public static <T, M> MapNotNullGatherer<T, M> mapNotNull(Function<T, M> mapper) {
return new MapNotNullGatherer<>(mapper);
}
public static <T> FindFirstGatherer<T> findFirst(Predicate<T> predicate) {
return new FindFirstGatherer<>(predicate);
}
}
مثال على الاستخدام:
var money = List.of(
new Money(BigDecimal.valueOf(12), PLN),
new Money(BigDecimal.valueOf(11), PLN),
new Money(BigDecimal.valueOf(15), PLN)
);
System.out.println("Find first Gatherer");
money.stream()
.gather(MyGatherers.findFirst(m -> m.currency().equals(PLN)))
.forEach(System.out::println);
المخرجات:
Find first Gatherer
Money[amount=12, currency=PLN]
يقدم هذا الـ gatherer حلًا أنيقًا للحالات التي نحتاج فيها إلى أول عنصر مطابق فقط، مبسطًا العملية بأسلوب وظيفي أكثر.
الخلاصة
نظرت هذه المقالة نظرة معمقة في JEP-461: Stream Gatherers، وهي ميزة معاينة أُضيفت في Java 22. بدأنا بتفكيك مفاهيمها الأساسية ثم بنينا مجموعة من العمليات توضح فائدتها في حالات محددة. وتجعل هذه التجارب من الواضح أن هذا التجريد الجديد في Stream API يحسّن كثيرًا قابلية التخصيص وإعادة الاستخدام والوضوح العام لعمليات التدفقات – وهي خطوة مرحب بها إلى الأمام في معالجة البيانات في Java.
في المقالة التالية سنطلق الإمكانات الكاملة لـ Stream Gatherers بالنظر في gatherers المدمجة وفي كيفية تركيب Gatherer من Gatherers أخرى.
شاركونا آراءكم في هذا التحسين وفي فرص تحوله إلى ميزة مستقرة في إصدارات Java القادمة. فكما أرى، إنه تغيير مثير يجعل العمل مع التدفقات أكثر متعة وكفاءة في آن واحد.