beginnersbook.com

  • Home
  • All Tutorials
    • Learn Servlet
    • Learn JSP
    • Learn JSTL
    • Learn C
    • Learn C++
    • Learn MongoDB
    • Learn XML
    • Learn Python
    • Learn Perl
    • Learn Kotlin
    • Learn jQuery
  • Core Java
  • OOPs
  • Collections
  • Java I/O
  • JSON
  • DBMS

Random shuffling of an array in Java

By Chaitanya Singh | Filed Under: Java Tutorials

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
class ShuffleArrayExample {
 
  public static void main(String[] args) {
 
    // String Array
    String[] stringArray = 
        new String[] { "FF", "PP", "AA", "OO", "DD" };

    // converting array to a List
    List<String> list = Arrays.asList(stringArray);

    // Shuffling list elements
    Collections.shuffle(list);
 
    System.out.println("String Array: ");
    for (String str : list) {
       System.out.println(str);
    }
 
    Integer[] intArray = new Integer[]{11, 22, 33, 44, 55};
    /* Rememeber: If you define the array like this:
     * int[] array = new int[]{1, 2, 3, 4}; then the below 
     * method won't work as it doesn't work for primitive types
     */
 
    List<Integer> list2 = Arrays.asList(intArray);

    // Shuffling list elements
    Collections.shuffle(list2);
 
    System.out.println("Int Array: ");
    for (int num : list2) {
       System.out.println(num);
    }
  }
}

Output:

String Array: 
FF
OO
PP
DD
AA
Int Array: 
33
55
11
22
44

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Java Tutorial

  • Java Index
  • Java Introduction
  • JVM - Java Virtual Machine
  • First Java Program
  • Variables
  • Data Types
  • Operators

Java Control Statements

  • Java If-else
  • Java Switch-Case
  • Java For loop
  • Java while loop
  • Java do-while loop
  • Continue statement
  • break statement

OOPs Concepts

  • OOPs Concepts
  • Constructor
  • Static keyword
  • Inheritance
  • Types of inheritance
  • Aggregation
  • Association
  • Super Keyword
  • Method overloading
  • Method overriding
  • Overloading vs Overriding
  • Polymorphism
  • Types of polymorphism
  • Static and dynamic binding
  • Abstract class and methods
  • Interface
  • Abstract class vs interface
  • Encapsulation
  • Packages
  • Access modifiers
  • Garbage Collection
  • Inner classes
  • Static import
  • Static constructor
  • Java Interview Q

MORE ...

  • Java 8 Features
  • Java 9 Features
  • Java Conversion
  • Java String
  • Exception handling
  • Java Multithreading
  • Java I/O
  • Java Serialization
  • Java Regex
  • Java AWT
  • Java Swing
  • Java Enum
  • Java Annotations
  • Java main method

Copyright © 2012 – 2022 BeginnersBook . Privacy Policy . Sitemap