// Java program to count the number // of occurrence of a word in // the given string given string import java.io.*; class GFG { static int countOccurences(String str, String word) { // split the string by spaces in a String a[] = str.split(" "); // search for pattern in a int count = 0; for (int i = 0; i < a.length; i++) { // if match found increase count if (word.equals(a[i])) count++; } return count; } // Driver code public static void main(String args[]) { String str = "GeeksforGeeks A computer science portal for geeks "; String word = "portal"; System.out.println(countOccurences(str, word)); } } |
Showing posts with label programming. Show all posts
Showing posts with label programming. Show all posts
Tuesday, 22 January 2019
Friday, 18 January 2019
ITV-JAVA-COLLECTION-Programming-How to Remove Duplicates from ArrayList in Java
How to Remove Duplicates from ArrayList in Java
Given an ArrayList with duplicate values, the task is to remove the duplicate values from this ArrayList in Java.
Examples:
Input: List = [1, 10, 2, 2, 10, 3, 3, 3, 4, 5, 5] Output: List = [1, 10, 2, 3, 4, 5] Input: List = ["G", "e", "e", "k", "s"] Output: List = ["G", "e", "k", "s"]
Using Iterator
Approach:- Get the ArrayList with duplicate values.
- Create another ArrayList.
- Traverse through the first arraylist and store the first appearance of each element into the second arraylist using contains() method.
- The second ArrayList contains the elements with duplicates removed.
Below is the implementation of the above approach:// Java program to remove duplicates from ArrayListimportjava.util.*;publicclassGFG {// Function to remove duplicates from an ArrayListpublicstatic<T> ArrayList<T> removeDuplicates(ArrayList<T> list){// Create a new ArrayListArrayList<T> newList =newArrayList<T>();// Traverse through the first listfor(T element : list) {// If this element is not present in newList// then add itif(!newList.contains(element)) {newList.add(element);}}// return the new listreturnnewList;}// Driver codepublicstaticvoidmain(String args[]){// Get the ArrayList with duplicate valuesArrayList<Integer>list =newArrayList<>(Arrays.asList(1,10,1,2,2,3,3,10,3,4,5,5));// Print the ArraylistSystem.out.println("ArrayList with duplicates: "+ list);// Remove duplicatesArrayList<Integer>newList = removeDuplicates(list);// Print the ArrayList with duplicates removedSystem.out.println("ArrayList with duplicates removed: "+ newList);}}Output:
ArrayList with duplicates: [1, 10, 1, 2, 2, 3, 3, 10, 3, 4, 5, 5] ArrayList with duplicates removed: [1, 10, 2, 3, 4, 5]
Using LinkedHashSet
A better way (both time complexity and ease of implementation wise) is to remove duplicates from an ArrayList is to convert it into a Set that does not allow duplicates. Hence LinkedHashSet is the best option available as this do not allows duplicates as well it preserves the insertion order.Approach:- Get the ArrayList with duplicate values.
- Create a LinkedHashSet from this ArrayList. This will remove the duplicates
- Convert this LinkedHashSet back to Arraylist.
- The second ArrayList contains the elements with duplicates removed.
Below is the implementation of the above approach:
// Java program to remove duplicates from ArrayListimportjava.util.*;publicclassGFG {// Function to remove duplicates from an ArrayListpublicstatic<T> ArrayList<T> removeDuplicates(ArrayList<T> list){// Create a new LinkedHashSetSet<T> set =newLinkedHashSet<>();// Add the elements to setset.addAll(list);// Clear the listlist.clear();// add the elements of set// with no duplicates to the listlist.addAll(set);// return the listreturnlist;}// Driver codepublicstaticvoidmain(String args[]){// Get the ArrayList with duplicate valuesArrayList<Integer>list =newArrayList<>(Arrays.asList(1,10,1,2,2,3,10,3,3,4,5,5));// Print the ArraylistSystem.out.println("ArrayList with duplicates: "+ list);// Remove duplicatesArrayList<Integer>newList = removeDuplicates(list);// Print the ArrayList with duplicates removedSystem.out.println("ArrayList with duplicates removed: "+ newList);}}Output:
ArrayList with duplicates: [1, 10, 1, 2, 2, 3, 10, 3, 3, 4, 5, 5] ArrayList with duplicates removed: [1, 10, 2, 3, 4, 5]
Using Java 8 Stream.distinct()
You can use the distinct() method from the Stream API. The distinct() method return a new Stream without duplicates elements based on the result returned by equals() method, which can be used for further processing. The actual processing of Stream pipeline starts only after calling terminal methods like forEach() or collect().Approach:- Get the ArrayList with duplicate values.
- Create a new List from this ArrayList.
- Using Stream().distinct() method which return distinct object stream.
- convert this object stream into List
Below is the implementation of the above approach:// Java program to remove duplicates from ArrayListimportjava.util.ArrayList;importjava.util.Arrays;importjava.util.List;importjava.util.stream.Collectors;// Program to remove duplicates from a List in Java 8classGFG{publicstaticvoidmain(String[] args){// input list with duplicatesList<Integer> list =newArrayList<>(Arrays.asList(1,10,1,2,2,3,10,3,3,4,5,5));// Print the ArraylistSystem.out.println("ArrayList with duplicates: "+ list);// Construct a new list from the set constucted from elements// of the original listList<Integer> newList = list.stream().distinct().collect(Collectors.toList());// Print the ArrayList with duplicates removedSystem.out.println("ArrayList with duplicates removed: "+ newList);}}Output:
ArrayList with duplicates: [1, 10, 1, 2, 2, 3, 10, 3, 3, 4, 5, 5] ArrayList with duplicates removed: [1, 10, 2, 3, 4, 5]
Recommended Posts:
- Remove all elements from the ArrayList in Java
- How to remove an element from ArrayList in Java?
- Remove repeated elements from ArrayList in Java
- ArrayList and LinkedList remove() methods in Java with Examples
- ArrayList of ArrayList in Java
- Java.util.ArrayList.addall() method in Java
- ArrayList in Java
- Arraylist.contains() in Java
- Java.util.ArrayList.add() Method in Java
- Java.util.Arraylist.indexOf() in Java
- ArrayList isEmpty() in Java with example
- ArrayList trimToSize() in Java with example
- Initialize an ArrayList in Java
- Array of ArrayList in Java
- ArrayList vs LinkedList in Java
Subscribe to:
Posts (Atom)
40 Latest Interview Questions and Answers on Spring, Spring MVC, and Spring Boot
40 Latest Interview Questions and Answers on Spring, Spring MVC, and Spring Boot 1. What is Tight Coupling? When a class (ClassA) is depen...
-
ITV-JDBC-Why we use Class.forName(“oracle.jdbc.driver.OracleDriver”) while connecting to a database?1) Why we use Class.forName(“oracle.jdbc.driver.OracleDriver”) while connecting to a database? https://stackoverflow.com/questions/2007858...
-
1. Introduction In Spring MVC, the DispatcherServlet acts as front controller – receiving all incoming HTTP requests and processing ...
-
1.A)How HasMap works? HashMap in Java works on hashing principle. It is a data structure which allows us to store obj...