Saturday, 25 May 2024

Interview question java practical

Take a string and remove duplicate chars.


 import java.util.stream.Collectors;

public class Main {

  public static void main(String[] args) {

    System.out.println("Hello world!");

    String myName="pawan";

    String removedname=removeDuplicates(myName);

      System.out.println(removedname);

    

  }

  public static String removeDuplicates(String str) {

      // Convert the string to a stream of characters, remove duplicates and collect back to a string

      return str.chars()

                .distinct()

                .mapToObj(c -> String.valueOf((char) c))

                .collect(Collectors.joining());

  }

}

No comments:

Post a Comment