java remove duplicates from string array

we can remove duplicates from a string array using a combination of a Set and an array. A Set is a collection that does not allow duplicate elements, so by adding the elements of the array to a Set, any duplicates will be automatically removed.

Here is an example of how to remove duplicates from a string array:

String[] array = {"a", "b", "c", "a", "d", "b"};

Set<String> set = new HashSet<>(Arrays.asList(array));

String[] uniqueArray = set.toArray(new String[set.size()]);


In this example, we first create a string array with duplicate values. We then create a new HashSet and pass the array to its constructor, which automatically removes any duplicates. We then use the toArray() method of the Set to convert it back to an array, which now only contains unique values.

It's important to note that the order of the elements in the array is not guaranteed to be preserved after removing duplicates using this method. If you want to maintain the order of the elements in the array, you can use a List or a LinkedHashSet instead of a HashSet.

Removing duplicates from a string array in Java can be achieved by converting the array to a Set, which automatically removes any duplicates, and then converting it back to an array. This method is efficient and easy to implement, and it can be used to remove duplicates from any type of array.


In Java 8, can use the Stream API to remove duplicates from a string array. The Stream API provides a functional and declarative way of processing collections of data, including arrays. Here is an example of how to use the Stream API to remove duplicates from a string array:


String[] array = {"a", "b", "c", "a", "d", "b"};

String[] uniqueArray = Arrays.stream(array)
                             .distinct()
                             .toArray(String[]::new);

In this example, we first create a string array with duplicate values. We then create a stream of the array using the Arrays.stream() method, and then use the distinct() method to remove the duplicates. Finally, we use the toArray() method to convert the stream back to an array, which now only contains unique values.

It's important to note that the order of the elements in the array is not guaranteed to be preserved after removing duplicates using this method. If you want to maintain the order of the elements in the array, you can use LinkedHashSet instead of the distinct() method, and then convert it back to the array.

In summary, in Java 8, you can use the Stream API to remove duplicates from a string array by creating a stream of the array and using the distinct() method to remove the duplicates. This method is efficient and easy to implement, and it can be used to remove duplicates from any type of array, it's a functional and declarative way of processing collections of data.

in both cases, the order of the elements in the array is not guaranteed to be preserved after removing duplicates, if you want to maintain the order you can use a List or a LinkedHashSet instead of a HashSet or use the distinct() method.

Java 8 provides multiple ways to remove duplicates from a string array using the Stream API, you can use the distinct() method or a collection such as a Set to remove duplicates, both methods are efficient and easy to implement.

what happens when a constructor is defined for an interface?

  • Interfaces in Java do not have constructors. An interface is a blueprint for a class and it cannot be instantiated. An interface defines a set of methods and variables that a class must implement, but it does not contain any implementation for those methods.
  • Java does not allow constructors to be defined in an interface, because the purpose of an interface is to define a set of methods that can be implemented by a class, and not to provide an implementation for those methods. Constructors are used to initialize an object, but since an interface cannot be instantiated, there is no object to initialize.
  • If you try to define a constructor in an interface, the compiler will throw an error: "Interface methods cannot have a body."
  • However, you can have a default method in an interface, which is a method with a defined body, but it is not a constructor.
  • In summary, constructors are not allowed in interfaces, because interfaces are used to define a set of methods that can be implemented by a class, and not to provide an implementation for those methods.
  •  In Java 8 and later versions, the concept of a default method has been introduced. A default method is a method that has a defined body and can be used to provide a default implementation for a method in an interface, but it's not a constructor.

  •  If you try to define a constructor in an interface, it will result in a compilation error.
  • Interfaces in Java do not have constructors. An interface is a blueprint for a class and it cannot be instantiated. An interface defines a set of methods and variables that a class must implement, but it does not contain any implementation for those methods.

  • When the compiler encounters a constructor definition in an interface, it will throw an error because constructors are not allowed in interfaces. The error message will typically be similar to "Interface methods cannot have a body" or "Illegal combination of modifiers: 'constructor' and 'interface'".


How to print array in java

 To print an array in Java, you can use a for loop to iterate through the array and print each element. Here is an example of how to print an array of integers:

Here is a simple program that explains how to print an array of integers in java

  1. int[] myArray = {1, 2, 3, 4, 5};
  2. for (int i = 0; i < myArray.length; i++) {
  3.     System.out.print(myArray[i] + " ");
  4. }

This will print the following output: "1 2 3 4 5".

Alternatively:  Arrays.toString(myArray) and directly print the array.

System.out.println(Arrays.toString(myArray));

This will also print the array in same format "1 2 3 4 5"

We can also use the enhanced for loop (also known as the "for-each" loop) to print an array in Java. This type of loop automatically iterates through each element in the array, making it more concise and easier to read than a traditional for loop:

  1. for (int element : myArray) {
  2.     System.out.print(element + " ");
  3. }

This will also print the same output as the previous example "1 2 3 4 5".

When printing arrays of other types, such as Strings or objects, we can use the same approach. For example, if you have an array of Strings, you can use the enhanced for loop to print each element:

java print array

This will print the following output: "Hello World".

It's worth noting that, the Arrays.toString() method will work for all types of arrays, including arrays of objects, it will call the toString() method of each element in the array.

In case of the custom class objects, you may need to override the toString() method of the class.

Another way to print an array in Java is to use the Arrays.deepToString() method if the array is a multi-dimensional array. This method is similar to Arrays.toString(), but it can handle multi-dimensional arrays and it will recursively call itself for each sub-array. Here's an example of how to use Arrays.deepToString() to print a 2D array:

  1. int[][] my2DArray = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
  2. System.out.println(Arrays.deepToString(my2DArray))

This will print the following output: "[[1, 2, 3], [4, 5, 6], [7, 8, 9]]".

we can also use the java.util.Arrays.stream() method to print an array in Java 8 and later versions. This method returns a stream of the array's elements, which can then be passed to various stream operations such as forEach(). Here's an example of how to use Arrays.stream() to print an array:

int[] myArray = {1, 2, 3, 4, 5};

Arrays.stream(myArray).forEach(System.out::print);

This will also print the same output as the previous examples "1 2 3 4 5".

It's worth noting that when you use the Arrays.stream() method to print an array, it does not add any spaces or newlines between the elements, unlike the for loop and enhanced for loop. If we want to add spaces or newlines, you can use the map() method to transform each element into a string, and then use the forEach() method to print each string.

Java enum constructor

In Java, an enumeration is a special kind of class that represents a fixed number of predefined values. The values are defined as enum constants, which are static and final fields of the enumeration.

When you define an enum, you can also define a constructor for it, which is called when each enum constant is created. The constructor is passed the values of the constant's fields and can use those values to initialize the constant.

Here's an example of an enumeration called Size with a constructor that takes a single String argument:


In this example, the Size enumeration has four constants: SMALL, MEDIUM, LARGE, and EXTRA_LARGE. Each constant has an associated abbreviation, which is passed to the constructor when the constant is created. The constructor sets the value of the abbreviation field to the passed-in value.

You can call the constructor explicitly or it will be called automatically when enum constants are created, so the following code:

Size s = Size.SMALL;

is equivalent to

Size s = new Size("S");

When you define constructors for your enum, it is a best practice to make them private. So that no other classes can create an instance of your Enum. This way you can only use the predefined values of the Enum and not create any new value on runtime.

Java program to check valid Balanced parentheses

Balanced parentheses:
  •   A string which contains below characters in correct order.
  •  "{}" "[]" "()"
  • We need to check whether given string has valid order of parenthesis order.
  • If the parenthesis characters are placed in order then we can say its valid parentheses or balanced parentheses.
  • If the parentheses characters are not in correct order or open and close then we can say it is not balanced or invalid parenthesis.
  • Program to check given string has a valid parenthesis or not.

#1: Java example program to check given string has valid parenthesis or not.


  1. package instanceofjava;

  2. import java.util.Stack;

  3. public class BalancedParenthensies {

  4. public static void main(String[] args) {
  5. System.out.println(checkParenthensies("{(xxx,yyy)}"));
  6. System.out.println(checkParenthensies("{)(acd,bcvfs}"));
  7. System.out.println(checkParenthensies("{(xxx},yyy)"));
  8. System.out.println(checkParenthensies("[(xxx),yyy]"));
  9. }
  10. public static boolean checkParenthensies(String str) {
  11.         Stack<Character> object  = new Stack<Character>();
  12.         for(int i = 0; i < str.length(); i++) {
  13.             char ch = str.charAt(i);
  14.             if(ch == '[' || ch == '(' || ch == '{' ) {     
  15.             object.push(ch);
  16.             } else if(ch == ']') {
  17.                 if(object.isEmpty() || object.pop() != '[') {
  18.                     return false;
  19.                 }
  20.             } else if(ch == ')') {
  21.                 if(object.isEmpty() || object.pop() != '(') {
  22.                     return false;
  23.                 }           
  24.             } else if(ch == '}') {
  25.                 if(object.isEmpty() || object.pop() != '{') {
  26.                     return false;
  27.                 }
  28.             }
  29.         }
  30.         return object.isEmpty();
  31.     }
  32. }

Output:
  1. true
  2. false
  3. false
  4. true

check valid java balanced parenthesis


Java 8 stream filter method example program

  • We can use java 8 stream class filter method to filter the values from a list /map in java
  • By Using filter() and collect() methods of stream class we can achieve this.
  • Lets see an example program to filter value from list without using java 8 streams and with java 8 stream filter.



#1: Java Example program to filter . remove value from list without using java 8 stream

  1. package com.instanceofjava.filtermethodjava8

  2. import java.util.ArrayList;
  3. import java.util.Arrays;
  4. import java.util.List;

  5. /**
  6.  * @author www.Instanceofjava.com
  7.  * @category interview programs
  8.  * 
  9.  * Description: Remove value from list without using java 8 stream filter method
  10.  *
  11.  */
  12. public class fillterListJava8{
  13. private static List<String> filterList(List<String> fruits, String filter) {
  14.         List<String> result = new ArrayList<>();
  15.         for (String fruit : fruits) {
  16.             if (!filter.equals(fruit)) { 
  17.                 result.add(fruit);
  18.             }
  19.         }
  20.         return result;
  21.     }
  22. public static void main(String[] args) {
  23. List<String> fruits = Arrays.asList("apple", "banana", "lemon");
  24.  
  25. System.out.println("Before..");
  26.  
  27. for (String str : fruits) {
  28.             System.out.println(str);    
  29.         }
  30.  
  31.         List<String> result = filterList(fruits, "lemon");
  32.         System.out.println("After..");
  33.         for (String str : result) {
  34.             System.out.println(str);    
  35.         }
  36. }
  37. }

Output:
  1. Before..
  2. apple
  3. banana
  4. lemon
  5. After..
  6. apple
  7. banana

#2: Java Example program to filter . remove value from list using java 8 java.util.stream

  1. package com.instanceofjava.java8;

  2. import java.util.ArrayList;
  3. import java.util.Arrays;
  4. import java.util.List;
  5. import java.util.stream.Collectors;

  6. /**
  7.  * @author www.Instanceofjava.com
  8.  * @category interview programs
  9.  * 
  10.  * Description: Remove value from list using java 8 stream filter method
  11.  *
  12.  */

  13. public class filterMethodOfStream {

  14. public static void main(String[] args) {
  15. List<String> fruits = Arrays.asList("apple", "banana", "lemon");
  16. String value="lemon";
  17. List<String> result = fruits.stream()                
  18.                 .filter(line -> !value.equals(line))     
  19.                 .collect(Collectors.toList());             
  20.         result.forEach(System.out::println); 
  21.        
  22.         for (String str : result) {
  23.             System.out.println(str);    
  24.         }
  25. }

  26. }






Output:


java 8 stream filter method

How to remove html tags from string java

  • If you want to remove html tags from a string in java you need to use regex.
  • Using java regex we can trim/remove html tags from given string.
  • Lets see a java example program on how can we remove html code or html tags from a string in java.
  • Input String : <B>hello</B>
  • output: hello



#1: Java Example program to remove html tags from a string

  1. package com.instanceofjava.removehtmltags;
  2. /**
  3.  * @author www.Instanceofjava.com
  4.  * @category interview programs
  5.  * 
  6.  * Description: java convert html to plain text/ trim html code from string in java
  7.  *
  8.  */
  9. public class RemoveHtmlTags {

  10. public static void main(String[] args) {
  11. String htmlStr = "<p>Java Program to remove html tags from a String</p>";
  12.         System.out.println(htmlStr);
  13.         htmlStr = htmlStr.replaceAll("\\<.*?\\>", "");
  14.         System.out.println(htmlStr);
  15. }

  16. }

Output:
  1. <p>Java Program to remove html tags from a String</p>
  2. Java Program to remove html tags from a String

remove html code from string in java

Select Menu