Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

IN JAVA. please post as copyable text code, Not an image. Write a method called

ID: 3836934 • Letter: I

Question

IN JAVA. please post as copyable text code, Not an image.

Write a method called retainEvenLength that takes a Set of strings as a parameter and that retains only the strings of even length from the set, removing all other strings. For example, if a set called s stores the following values: [I, Sam, am, and, do, eggs, green, ham, like, not, them] and the following call is made: retainEvenLength(s); then s should store the following values after the call: [am, do, eggs, like, them] Turn in just the code for this method and your console output. I will test your code with the examples values above.

Explanation / Answer

JAVA :

import java.util.*;
import java.io.*;

class Main{
  
   public static String[] retainEvenLength(String str[]){
      
       //Initializing arraylist to store the answer
       ArrayList<String> al = new ArrayList();
       //Iterating through all the strings in the input
       for(String x : str){
           //Add to the list if the length of the string is even
           if(x.length()%2==0){
               al.add(x);
           }
       }
       //Initialize array to hold the answer
       String ans[] = new String[al.size()];
       int ind=0;
       //Add the elements in the arraylist to the answer
       for(String x : al){
           ans[ind++] = x;
       }
       return ans;
   }
  
   public static void main(String args[]){
       String str[] = new String[]{"I","Sam","am","and","do","eggs","green","ham","like","not","them"};
       String[] ans = retainEvenLength(str);
       for(String x : ans)
       System.out.println(x);
   }
}

OUTPUT :

am
do
eggs
like
them