इस लेख में हम समझेंगे कि Java में कलेक्शन के एलिमेंट्स को कैसे शफल (फेरबदल) किया जाता है। कलेक्शन एक फ्रेमवर्क है जो ऑब्जेक्ट्स के समूह को स्टोर और मैनिपुलेट करने की आर्किटेक्चर प्रदान करता है।
उदाहरण
इनपुट:
Input list: [Java, program, is, fun, and, easy]
आउटपुट:
The shuffled list is: [is, easy, program, and, fun, Java]
एल्गोरिदम
- शुरुआत
- एक ArrayList
input_listडिक्लेयर करें - मान परिभाषित करें
shuffle()फंक्शन का उपयोग करके लिस्ट के एलिमेंट्स को शफल करें- परिणाम प्रदर्शित करें
- रोकें
उदाहरण 1: मुख्य फंक्शन में सभी ऑपरेशन
import java.util.*;
public class Demo {
public static void main(String[] args) {
ArrayList<String> input_list = new ArrayList<String>();
input_list.add("Java");
input_list.add("program");
input_list.add("is");
input_list.add("fun");
input_list.add("and");
input_list.add("easy");
System.out.println("The list is defined as:" + input_list);
Collections.shuffle(input_list, new Random());
System.out.println("The shuffled list is: \n" + input_list);
}
}
आउटपुट
The list is defined as:[Java, program, is, fun, and, easy] The shuffled list is: [is, Java, fun, program, easy, and]
उदाहरण 2: ऑब्जेक्ट-ओरिएंटेड दृष्टिकोण
import java.util.*;
public class Demo {
static void shuffle(ArrayList<String> input_list) {
Collections.shuffle(input_list, new Random());
System.out.println("The shuffled list is: \n" + input_list);
}
public static void main(String[] args) {
ArrayList<String> input_list = new ArrayList<String>();
input_list.add("Java");
input_list.add("program");
input_list.add("is");
input_list.add("fun");
input_list.add("and");
input_list.add("easy");
System.out.println("The list is defined as:" + input_list);
shuffle(input_list);
}
}
आउटपुट
The list is defined as:[Java, program, is, fun, and, easy] The shuffled list is: [fun, and, Java, easy, is, program]