← Back to Advanced Java Course | Chapter 3: Functional Programming | Lesson 6 of 6

Java के Collectors

Collectors किसी stream के results को एक list, map या summary में इकट्ठा करते हैं, जैसे किसी conveyor belt के आखिर में sorted items को containers में रखना। वे group, split, और join भी कर सकते हैं।
Syntax
java
stream.collect(Collectors.toList());
stream.collect(Collectors.toSet());
stream.collect(Collectors.groupingBy(item -> key));
stream.collect(Collectors.joining(", "));

What is a Collector?

एक Collector किसी Stream pipeline में terminal operation के रूप में उपयोग होता है, और इसका काम stream के elements को किसी अंतिम container में इकट्ठा करना है, जैसे List, Set, या Map, इस पर निर्भर करते हुए कि आप कौन सा Collector चुनते हैं।

उदाहरण: What is a Collector?

java
// Import java.util.* so it can be used by its short name
import java.util.*;
// Import java.util.stream.* so it can be used by its short name
import java.util.stream.*;
// Define the class Main
public class Main {
	// Program entry point: the JVM starts running here
	public static void main(String[] args) {
		List<String> names = Stream.of("Ana", "Bob", "Cy")
			.collect(Collectors.toList());
		// Print a line to the console
		System.out.println(names);
	}
}

Collecting into Maps

आप Collectors.toMap() का उपयोग करके stream elements को सीधे एक Map में इकट्ठा कर सकते हैं, जिसके लिए आपको एक key-mapper function और एक value-mapper function दोनों देने होंगे जो बताते हैं कि किसी stream element से हर map entry कैसे निकाली जाए।

उदाहरण: Collecting into Maps

java
// Import java.util.* so it can be used by its short name
import java.util.*;
// Import java.util.stream.* so it can be used by its short name
import java.util.stream.*;
// Define the class Main
public class Main {
	// Program entry point: the JVM starts running here
	public static void main(String[] args) {
		List<String> names = List.of("Ana", "Bob", "Cy");
		// Create a stream from the collection to process it step by step
		Map<String, Integer> lengths = names.stream()
			.collect(Collectors.toMap(name -> name, String::length));
		// Print a line to the console
		System.out.println(lengths);
	}
}

Grouping Data

आप Collectors.groupingBy() collector का उपयोग करके stream elements को किसी shared attribute के आधार पर group कर सकते हैं, जो एक ऐसा Map return करता है जिसकी keys grouping categories हैं और जिनकी values हर group के elements की lists हैं।

उदाहरण: Grouping Data

java
// Import java.util.* so it can be used by its short name
import java.util.*;
// Import java.util.stream.* so it can be used by its short name
import java.util.stream.*;
// Define the class Main
public class Main {
	// Program entry point: the JVM starts running here
	public static void main(String[] args) {
		List<String> words = List.of("apple", "banana", "avocado", "blueberry");
		// Create a stream from the collection to process it step by step
		Map<Character, List<String>> grouped = words.stream()
			.collect(Collectors.groupingBy(w -> w.charAt(0)));
		// Print a line to the console
		System.out.println(grouped);
	}
}

Partitioning Data

Partitioning grouping का एक special case है जहां grouping key हमेशा एक boolean होती है, data को बिल्कुल दो buckets में बांटते हुए। stream elements को एक ही pass में एक true list और एक false list में बांटने के लिए किसी predicate के साथ Collectors.partitioningBy() का उपयोग करें।

उदाहरण: Partitioning Data

java
// Import java.util.* so it can be used by its short name
import java.util.*;
// Import java.util.stream.* so it can be used by its short name
import java.util.stream.*;
// Define the class Main
public class Main {
	// Program entry point: the JVM starts running here
	public static void main(String[] args) {
		List<Integer> nums = List.of(1, 2, 3, 4, 5, 6);
		// Create a stream from the collection to process it step by step
		Map<Boolean, List<Integer>> partitioned = nums.stream()
			.collect(Collectors.partitioningBy(n -> n % 2 == 0));
		// Print a line to the console
		System.out.println(partitioned);
	}
}

Joining and Summarizing

आप Collectors.joining() का उपयोग करके string elements को एक delimited string में जोड़ सकते हैं, optionally एक delimiter, prefix, और suffix देते हुए। counts, sums, या averages जैसे running statistics compute करने के लिए, इसके बजाय Collectors.summarizingInt()-style collector का उपयोग करें।

उदाहरण: Joining and Summarizing

java
// Import java.util.* so it can be used by its short name
import java.util.*;
// Import java.util.stream.* so it can be used by its short name
import java.util.stream.*;
// Define the class Main
public class Main {
	// Program entry point: the JVM starts running here
	public static void main(String[] args) {
		List<String> names = List.of("Ana", "Bob", "Cy");
		// Create a stream from the collection to process it step by step
		String joined = names.stream().collect(Collectors.joining(", ", "[", "]"));
		// Create a stream from the collection to process it step by step
		IntSummaryStatistics stats = names.stream()
			.collect(Collectors.summarizingInt(String::length));
		// Print a line to the console
		System.out.println(joined + " avg=" + stats.getAverage());
	}
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. Collectors.toMap का उपयोग करना जब दो elements एक जैसी key produce करें, जो IllegalStateException फेंकता है; तीसरे argument के रूप में एक merge function पास करें।
  2. Collectors.toMap में null value होना, जो NullPointerException फेंकता है।
  3. यह उम्मीद करना कि groupingBy insertion order बनाए रखेगा, जबकि यह default रूप से एक HashMap return करता है; अगर order मायने रखता है तो एक LinkedHashMap या TreeMap supplier पास करें।
चैप्टर सारांश
  • Lambda expressions और method references behavior लिखने का एक छोटा तरीका देते हैं।
  • Functional interfaces और Stream API filtering और mapping जैसे operations से data process करते हैं।
  • Optional उन values को handle करता है जो गायब हो सकती हैं, और Collectors stream results इकट्ठा करते हैं।
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.