Write a Java program to Find the element position in a reversed string array.

Write Java code to sort the given array in reverse alphabetical order and return the position of the given string in the array.

The return type of the output is an integer which is the position of given string value from the array.

Input and Output Format:

Input is a string array. The first element in the input represents the size the array

Assume the position of the first element is 1.

The output is an integer which is the position of the string variable.

Sample Input 1:

4

red

green

blue

ivory

ivory

Sample Output 1:

2

Sample Input 2:

3

grape

mango

apple

apple

Sample Output 2:

3

Find the element position in a reversed string array in Java.

import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class Main {
/**
* @param args
*/
public static void main(String[] args) {

Scanner sc=new Scanner(System.in);
int fr=sc.nextInt();
String a[]=new String[fr];
for(int i=0;i<fr;i++)
{
  a[i]=sc.next();
}
String ba=sc.next();
getvalues(a,ba);

}
public static void getvalues(String[] a, String b) {
ArrayList<String>al=new ArrayList<String>();
for(int i=0;i<a.length;i++)
{
al.add(a[i]);
}
System.out.println(al);
Collections.sort(al);
System.out.println(al);
Collections.reverse(al);
System.out.println(al);
for(int i=0;i<al.size();i++)
{
if(b.equals(al.get(i)))
{
System.out.println(i+1);
}
}
}
}

Add a Comment

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

eighteen − 18 =