×

Reverse a String using Collections in Java

Generally, a String is a grouping of characters. Yet, in Java, a String is an item that addresses a succession of characters. The Java.lang.String class is utilized to make a string object.

Syntax

<String_Type> <string_variable> = "<sequence_of_string>";

Example

String str = "Hello!";

There are two methods for making String objects:

  1. String literal
  2. New keyword

1. String Literal: Java String literal is made by utilizing twofold statements.

For Example: String s = "Victory"; 

2. New Keyword: The new keyword is used for creating the String.

For Example: String s=new String("Victory");

Program in Java

public class StringExample{    
public static void main(String args[]){    
String v1="python";// making string by Java string literal
char ch[]={'v','i','c','t','o','r','y'};    
String v2=new String();//changing over char to string
String v3=new String("example");// making Java string by new keyword
System.out.println(v1);    
System.out.println(v2);    
System.out.println(v3);    
}
}    

Output

Reverse a String using Collections in Java

Collections in Java

The Collection in Java is a framework that gives a plan to store and control the get-together of things. Java Collections can accomplish each of the endeavours that you perform on a piece of information, for example, looking, sorting out, joining, controlling, and erasure.

Java Collection implies a solitary unit of items. Java Collection structure gives different affiliation centres (Set, List, Queue, Deque) and classes (ArrayList, Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet). The Collection interface (Java.util.Collection) and Map interface (Java.util.Map) are the two primaries "root" points of interaction of Java assortment classes.

To make a string object, you really want the Java.lang.String class. Java programming utilizes UTF - 16 to address a string. Strings are unchanging with the goal that their inside state stays steady after the article is totally made. The string object performs different tasks, yet turn-around strings in Java are the most generally utilized capability.

Framework

A framework is a bunch of classes and points of interaction which give an instant design. To carry out another element or a class, there is a compelling reason needed to characterize a structure. Notwithstanding, an ideal item situated plan generally incorporates a structure with an assortment of classes to such an extent that every one of the classes plays out a similar sort of errand.

Classes in Collection

There are various classes in the Collection. A couple of classes give full execution, while the rest give a skeletal plan. The different classes are examined underneath:

  • AbstractCollection: This class executes the greater part of the connection points which are characterized in the assortment.
  • AbstractList: This class acquires the AbstractCollection class and executes the majority of the connection points in the List Interface.
  • AbstractQueue: This class acquires the AbstractCollection class and carries out the greater part of the connection points in the Queue Interface.
  • AbstractSequentialList: This class acquires the AbstractList class for usage in records that employ sequential access. Sequential access occurs when each word is iterated individually.
  • LinkedList: This class acquires the AbstractSequentialList class and executes connected records.
  • ArrayList: This class acquires the AbstractList class and executes a unique exhibit. A unique exhibit is the one where the size is pronounced at run time.
  • ArrayDeque: This class acquires the AbstractCollection class and executes the dequeue interface. It executes a twofold finished line dynamic in nature.
  • AbstractSet: This class acquires the AbstractCollection class and executes the greater part of the connection points in the rundown interface.
  • EnumSet: This class extends the AbstractSet class and uses enum components.
  • HashSet: This class secures the AbstractSet class and uses it with the hash table.
  • LinkedHashSet: This class acquires the HashSet class and allows for cycles in the extension request.
  • PriorityQueue: This class obtains the AbstractQueue class and employs it in the creation of need lines.
  • TreeSet: This class obtained the AbstractSet class and used it to construct a coordinated set in the tree.

Collections.reverse() Method in Java

The reverse() strategy for Collections class as the actual name proposes is utilized for turning around components been there up in the article in which they are put away. It switches the request for components in a rundown passed as a contention.

The accompanying model exhibits how to utilize Collections. Reverse () to turn around Java's String. Following are the finished advances:

Make a vacant ArrayList of characters and introduce it with characters of the given String utilizing String.toCharArray().

Switch the rundown utilizing java.util.Collections turn around() technique.

At long last, convert the ArrayList into String utilizing StringBuilder and return the framed String.

Example: 1

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
 class Main
{
   
    public static String reverse(String str)
    {
          if (str == null || str.equals("")) {
            return str;
        }
 
           List<Character> list = new ArrayList<Character>();
         for (char c: str.toCharArray()) {
            list.add(c);
        }
 
               Collections.reverse(list);
        return list.stream().map(String::valueOf).collect(Collectors.joining());
    }
 
    public static void main(String[] args)
    {
        String str = "Reverse me!";
         str = reverse(str);
         System.out.println("The reversed string is " + str);
    }
}

Output

Reverse a String using Collections in Java

The above arrangement initial proselytes ArrayList into StringBuilder, then StringBuilder into a string. We can straightforwardly change over ArrayList into a string by eliminating square sections, commas, and single spaces from it. The accompanying code utilizes String.replaceAll() to accomplish that. Regardless, this approach is extraordinarily inefficient and should be avoided, come what may.

Example: 2

import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
 
class Main
{
    // Method to reverse a string in Java using `Collections.reverse()`
    public static String reverse(String str)
    {
        if (str == null || str.equals("")) {
            return str;
        }
 
        List<Character> list = new ArrayList<Character>();
        for (char c: str.toCharArray()) {
            list.add(c);
        }
 
        
        Collections.reverse(list);
         return list.toString()
            .replaceAll("[,\\[\\]]", "")    // t h g i l e D   e i h c e T
            .replaceAll("  ", "@")          // t h g i l e D@ e i h c e T
            .replaceAll(" ", "")            // thgileD@eihceT
            .replaceAll("@", " ");          // !em esreveR
    }
 
    public static void main(String[] args)
    {
        String str = "Reverse me!";
         str = reverse(str);
         System.out.println("The reversed string is " + str);
    }

Output

Reverse a String using Collections in Java

That is tied in with switching a String utilizing the converse() strategy for Java Collections Framework.


Related Topics

Fall through in Java

In this article, you will be acknowledged about the fall through condition in Java along with an example program. Fall through It is a situation where there isn't a break statement in...

3 minutes read.

Highest precedence in Java

In Java, the operator is the first thing that springs to mind when discussing precedence. The order in which the operators in an expression are evaluated is controlled by a...

3 minutes read.

Java Integer numberOfTrailingZeros() method

The numberOfTrailingZeros()  method of Java Integer class returns the total number of zero bits following the lowest-order one-bit in the 2’s complement binary representation of the specified int value. Syntax public static...

1 minute read.

Java Password Generator

Generally, we must create a strong password for security reasons. In Java, there are numerous strategies for creating secure passwords. We will learn how to create a strong password in...

4 minutes read.

How to Convert String to double in Java

How to Convert String to double in java It is used if we have to perform mathematical operations on the string that contains a double number. When we get data from...

3 minutes read.

How to Convert String to boolean in Java

How to Convert String to boolean in Java There are two methods to convert String to boolean: Using parseBoolean(string) method Using valueOf(string) method If the string contains "True," "true," or "TRUE,"...

3 minutes read.

How to Convert Decimal to Hexadecimal in Java

How to Convert Decimal to Hexadecimal in Java The hexadecimal number uses 16 values to represent a number. Numbers from 0 to 9 represented by digits and the numbers from 10...

3 minutes read.

Java IO

It is a part of java libraries but is often known as I/O streams, file I/O, and file handling. The Java I/O concept satisfies the need for input processing and...

4 minutes read.

How to Solve the Deprecated Error in Java?

Deprecated Java methods should not be used because they are deprecated (often, there are better, more modern alternatives). API update. Until now, Java has kept everything backward compatible and never...

3 minutes read.

Java Command Line Arguments

Java command line arguments Command line argument is an input or argument to the program when you run the program. In Java, we can take the inputs from the console, and...

2 minutes read.

Prepared statement in Java

Prepared statement: A prepared statement is a statement that is pre-compiled SQL statement, and it is a sub-interface of a statement. Compared to other statement objects in java, Prepared Statement objects have...

3 minutes read.

How to Convert String to enum in Java?

In this article, we shall gain the complete knowledge about how to convert the string to enum in Java. The complete process that happens in the approach shall be discussed...

3 minutes read.

Java Map Generic

Java arrays maintain an ordered collection of things, and the index can be used to access the data (an integer). Unlike HashMap, which stores data as a Key/Value pair. We...

3 minutes read.

Convert Integer to Roman Numerals in Java

The main objective of this article is to convert the integers that are decimal values to the roman numbers. Problem statement: Write a software/program/code to convert any integer to a roman number. You...

10 minutes read.

TreeSet in Java

Java TreeSet with Example Java TreeSet implements the Navigable Set interface. It stores the objects in ascending order. It contains unique elements. Access and retrieval time is fast. It does not...

8 minutes read.

Java Integer compareUnsigned() method

The compareUnsigned() method of Integer class compares two int objects numerically by treating the values as unsigned. Syntax public static int compareUnsigned(int x , int y) Parameters The parameters ‘x’ and ‘y’ represent the...

1 minute read.

How to open the Java control panel

The many methods for launching the Java control panel will be covered in this section. We will also go through how the Java Control Panel can be used. Java Control Panel The...

2 minutes read.

Jagged Array in Java

Prerequisite We must first understand what Arrays are and Multi-dimensional Arrays are before we can learn about Jagged arrays. Java Arrays: A collection of data types that are similar is called an...

5 minutes read.

Java String subSequence() method

This method returns a new character sequence i.e. subsequence of current sequence Syntax: public CharSequence subSequence(int beginIndex, int endIndex) Parameter: beginIndex ? begin index, inclusive. endIndex ? end index, exclusive. Return: specified subsequnce Throws: It throws IndexOutOfBoundsException...

1 minute read.

Stack in Java

Java provides a number of collection frameworks to store the collection of objects. Among the collection of data structures " Stack " is one of them. Stack is one of...

5 minutes read.