Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

โปรแกรม Java เพื่อสับเปลี่ยนองค์ประกอบของคอลเลกชัน


ในบทความนี้ เราจะเข้าใจวิธีการสับเปลี่ยนองค์ประกอบของคอลเลกชัน คอลเล็กชันคือเฟรมเวิร์กที่จัดเตรียมสถาปัตยกรรมสำหรับจัดเก็บและจัดการกลุ่มของอ็อบเจ็กต์ JavaCollections สามารถบรรลุการดำเนินการทั้งหมดที่คุณดำเนินการกับข้อมูล เช่น การค้นหา การเรียงลำดับ การแทรก การจัดการ และการลบ

ด้านล่างนี้เป็นการสาธิตสิ่งเดียวกัน -

สมมติว่าข้อมูลที่เราป้อนคือ

Input list: [Java, program, is, fun, and, easy]

ผลลัพธ์ที่ต้องการจะเป็น

The shuffled list is:
[is, easy, program, and, fun, Java]

อัลกอริทึม

Step 1 - START
Step 2 - Declare an arraylist namely input_list.
Step 3 - Define the values.
Step 4 - Using the function shuffle(), we shuffle the elements of the list.
Step 5 - Display the result
Step 6 - Stop

ตัวอย่างที่ 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]