4

I have a java class which involves a String array and two for loops

for going through the array elements and prints them plus their redundancy in the

array as they are Strings .

I want someone help me to print each element (String) one time only even it

repeated in the array.

The following code prints some element in the array more than one time.

So comparison between elements of the array Needed

 public class myClassName {

 static String [] myArray = {"Khaled","Valderama","Daoud","Khaled","Rasheed","Daoud","Valderama","Khaled"};

      public static String [] getArray()

      {

      String str[] = new String[myArray.length];

     for(int i=0;i<myArray.length;i++)

       {

       str[i] = myArray[i].toString();

        }

       return str;

     }

     public static void main( String [] args)

     {

     String d [] = getArray();

     int noOftimesRepeated;

          for(int i=0;i<getArray().length;i++)

          {

          noOftimesRepeated=1;

          String currentName = d[i];

          for(int j=0;j<getArray().length;j++)

          {

          if(i!=j && d[i].equalsIgnoreCase(d[j]))

          {

          noOftimesRepeated = noOftimesRepeated+1;

          }


          }

          int j =0;


          System.out.println(d[i]+"\t" +"\t"+noOftimesRepeated);

  }

 }

}

Please Is there any solution without using .util.* package

I have a second trial but it out prints the one element and it redundancy

only.

 public class Javafool {

      static String [] myArray = {"Khaled","Valderama","Daoud","Khaled","Rasheed","Daoud","Valderama","Khalo","Valderama"};

     static String str2[] = new String[myArray.length];


     public static String [] getArray()
      {

      String str[] = new String[myArray.length];


      for(int i=0;i<myArray.length;i++)

      {

      str[i] = myArray[i].toString();

      }

      return str;

      }

      public static void main(String[] args) {

      String d [] = getArray();

      int noOftimesRepeated;

       sort(myArray);

       int no_of_repeat=1;

        String temp =null;

     int i   ;

      for(  i = 0;i<myArray.length-1;i++)

       {

           temp = myArray[i];

         myArray[i] = myArray[i+1];

         myArray[i+1] = temp;

       if(myArray[i].equals(temp))

       {

       no_of_repeat=  ++no_of_repeat;

       }

     }

      System.out.println(myArray[i]+""+temp+"\t"+"\t\t"+no_of_repeat);

      }

     public static void sort(String [] array) {

       String temp = null;

       for(int j=0;j<array.length;j++)
             {

         for(int i = 0; i<array.length-1;i++)
              {
           if(array[i].compareTo(array[i+1])<0)
                {

         temp = array[i];

         array[i] = array[i+1];

         array[i+1] = temp;

           }

           }}}}
4
  • I upvoted both answers. If your need is only to remove duplicates, use arjacsoh's solution. If you need to count occurrences of each String, use lulyon's solution. Commented Sep 9, 2013 at 12:10
  • Please Is there any solution without using .util.* package Commented Sep 9, 2013 at 12:20
  • Is it a requirement to absolutely avoid java.util.* package? I see some solutions without it (manual sorting?) but it is nearly equivalent as the methods exposed in java.util and it will likely be error prone. Commented Sep 9, 2013 at 12:24
  • s it a requirement to absolutely avoid java.util.* package? Yes Exactly. Commented Sep 9, 2013 at 12:26

12 Answers 12

3

Add the Strings to Set<String>, which eliminates duplicate values, and then print them:

List<String> list = Arrays.asList("Khaled", "Valderama",...);
Set<String> set = new LinkedHashSet<String>(list);

for(String s : set)
  System.out.println(s);
Sign up to request clarification or add additional context in comments.

Comments

2

Use Map<String, Integer>, String for the input string, Integer for the noOftimesRepeated counter.

Example:

Map<String , Integer> map = new HashMap<String , Integer>(); 

// Add and count str Repeated times.
map.put(str, map.get(str) + 1);

// output string and counter pair in map
System.out.println(map);

6 Comments

Please Is there any solution without using .util.* package
@ElhadiMamoun I have a more manual approach(require more code of course) by sorting the array first and count the neighbored strings. But the time complexity is o(nlogn), better than two nested forloop, which is o(n^2).
@Ruchira Thank you. code is not complete here, just an example.
@lulyon Is your new manual approach avoids java.util.*; package?
@ElhadiMamoun It could be. The first step, sorting, which can be manually implementing with Quicksort algorithm. The second step(counting the neighbored strings by a pass for string array) is itself avoid using java package.
|
1

If you absolutely don't want to use java.util, you can still sort by hand and remove adjacent duplicates :

public static void main(String[] args) {
  String [] myArray = {"Khaled","Valderama","Daoud","Khaled","Rasheed","Daoud","Valderama","Khaled"};
  sort(myArray);

  String last=null;
  for(int i = 0;i<myArray.length;i++) {
    if(last==null || !myArray[i].equals(last)) {
      last = myArray[i];
      System.out.print(last+", ");
    }
  }
}

/*
 * Very naive method to sort elements. You can improve this with a merge sort.
 * Arrays.sort() would do the same job in a better way.
 */
public static void sort(String [] array) {
  String temp = null;

  for(int j=0;j<array.length;j++) {
    for(int i = 0; i<array.length-1;i++) {
      if(array[i].compareTo(array[i+1])<0) {
        temp = array[i];
        array[i] = array[i+1];
        array[i+1] = temp;
      }
    }
  }
}

3 Comments

Your code is good as not repeating the displaying of elements but it doesn't count the number a of String redundancy
You have a sorted array. It is not very difficult to count occurrences of adjacent elements.
public static void main(String[] args) { String d [] = getArray(); int noOftimesRepeated; sort(myArray); int no_of_repeat=1; String temp =null; int i ; for( i = 0;i<myArray.length-1;i++) { temp = myArray[i]; myArray[i] = myArray[i+1]; myArray[i+1] = temp; if(myArray[i].equals(temp) ) { no_of_repeat= ++no_of_repeat; } I changed little into your code , now the code can prints the number of redundancy for one element only , can you guide me more plz?
0
public static void main(String[] args) {
    List<String> myArray = Arrays.asList("Khaled","Valderama","Daoud","Khaled","Rasheed","Daoud","Valderama","Khaled");

    Set<String> sets = new HashSet<String>();

    sets.addAll(myArray);

    System.out.println(sets);
}

Output: [Khaled, Valderama, Rasheed, Daoud]

Comments

0

You can do as below,

String[] myArray = { "Khaled", "Valderama", "Daoud", "Khaled",
        "Rasheed", "Daoud", "Valderama", "Khaled" };
Set<String> sets = new HashSet<String>(Arrays.asList(myArray));
System.out.println(Arrays.toString(sets.toArray()));

Comments

0

try this. The for Loop will not be running fully for duplicate items

import java.util.ArrayList;
public class myClassName {

 static String [] myArray = {"Khaled","Valderama","Daoud","Khaled","Rasheed","Daoud","Valderama","Khaled"};
      public static String [] getArray()
      {
          String str[] = new String[myArray.length];
          for(int i=0;i<myArray.length;i++)
          {
              str[i] = myArray[i].toString();
          }
       return str;
     }

     public static void main( String [] args)
     {
         String d [] = getArray();
         int noOftimesRepeated;
         ArrayList<String> list = new ArrayList<String>();
          for(int i=0;i<getArray().length;i++)
          {
              if(list.contains(d[i]))
                    continue;
              noOftimesRepeated=1;

              for(int j=0;j<getArray().length;j++)
              {
                  if(i!=j && d[i].equalsIgnoreCase(d[j])  )
                  {
                      noOftimesRepeated = noOftimesRepeated+1;
                      list.add(d[i]);
                  }
              }
              System.out.println(d[i]+"\t" +"\t"+noOftimesRepeated);

          }
     }
}

1 Comment

Please Is there any solution without using .util.* package
0

You can use set. Set will avoid adding duplicates.

    String [] myArray = {"Khaled","Valderama","Daoud",
                        "Khaled","Rasheed","Daoud","Valderama","Khaled"};
    Set<String> set=new HashSet<>();
    for(String i:myArray){
        set.add(i);
    }
    System.out.println(set);

If you don't want to use java.util.* package try following way.

  String [] myArray = {"Khaled","Valderama","Daoud","Khaled","Rasheed","Daoud",
                       "Valderama","Khaled"};
    String[] newArr=new String[myArray.length];
    int j=0;
    for(String i:myArray){
        if(!Arrays.toString(newArr).contains(i)){
            newArr[j]=i;
            j++;
        }
    }

3 Comments

Please Is there any solution without using .util.* package
@ElhadiMamoun you can try my second way.
but your code involves Arrays which is a class in java.util. package
0

I agree with previous guy, firstly you should make you arraylist in a sequence, you can try the Quicksort algorithm,secondly you should compare current element with the previous one, if they equal, do not print it. it is easy, right?

you can extract your quicksort algorithm function to a util class, so you can use it in later development.

Comments

0

Aside from using Set, you can also create a list of unique items.

String [] myArray = {"Khaled", "Valderama", "Daoud", "Khaled", "Rasheed", "Daoud", "Valderama", "Khaled"};
List<String> myPrintList = new ArrayList<String>();        

for(String str : myArray){            
    if(!myPrintList.contains(str)){ // Check first if myPrintList contains the item already
        myPrintList.add(str); // Add if the list doesn't contain that item
    }
}

// Print list
for(String str : myPrintList){
    System.out.println(str);
}

EDIT based from comment:

Not sure why you do not want to use util package, but-

String [] myArray = {"Khaled", "Valderama", "Daoud", "Khaled", "Rasheed", "Daoud", "Valderama", "Khaled"};
StringBuilder uniqueNames = new StringBuilder(); // For storing all unique names separated by a pipe (|)        

for(String str : myArray){

    if(uniqueNames.indexOf(str) < 0){ // Check if str exists in builder yet
        uniqueNames.append(str); // Add str if it doesn't exist
        uniqueNames.append("|"); // Add delimiter                
    }

}

String[] myPrintArray = uniqueNames.toString().split("\\|"); // Get an array by splitting using the pipe delimiter

for(String str : myPrintArray){        
    System.out.println(str);
}

1 Comment

Please Is there any solution without using .util.* package
0

You dun need 2 for loop to do it. Just this 3 line of code will do! :D

final List<String> lst = Arrays.asList("Khaled","Valderama","Daoud","Khaled","Rasheed","Daoud","Valderama","Khaled");
    final Set<String> set = new HashSet<String>(lst);
    System.out.printf("Unique values: ", set);

If without *ulit package

You will need a custom sort method. The pseudo code can goes like that (Not a efficient way of doing)

"Given" lst array; 
Array temp = new Araay(lst.lenght); 

//two for loop for 
(int i = 0; i< lst.lenght; i++) { 
if(i==0){ 
temp[i] = lst[i]; // first array 
} 
for (int u = 0 ; u < lst.lenght; u ++){ 
//Write a code here if the lst[i] string is not equal to any temp[u] string, add then inside. Else dun care :) Cheers! 
} 
}

2 Comments

Please Is there any solution without using .util.* package
@ElhadiMamoun Yes there is, You will need a custom sort method. The pseudo code can goes like that (Not a efficient way of doing ) "Given" lst array; Array temp = new Araay(lst.lenght); //two for loop for (i = 0; i< lst.lenght; i++) { if(i==0){ temp[i] = lst[i]; // first array } for (u = 0 ; u < lst.lenght; u ++){ //Write a code here if the lst[i] string is not equal to any temp[u] string, add then inside. Else dun care :) Cheers! } }
0

I found the solution,(The following solution doesn't involve java.util

package , and it depends on Quicksort Algorithm).

Thank you all.

     public class Javafool 

     {

static String [] myArray = {"Khaled","Valderama","Daoud","Khaled","Rasheed","Daoud","Valderama","Khalo","Valderama","Daoud"};

static String str2[] = new String[myArray.length];

     public static void main(String[] args)

     {

     int [] noOftimesRepeated;

      sort(myArray);

      int no_of_repeat=1;

      String temp =null;

       int i   ;

       int count = 0;

       String previous = null;

      for (String s : myArray) 

      {

     if (s.equals(previous))

     {

     count++;
     } 

     else 

     {

     if( previous !=null)

     System.out.println(previous + " :" + count);

     previous = s;

     count = 1;

     }

     }

     if (myArray.length > 0)

    {

    System.out.println(previous + " :" + count);

    }

    }

   public static void sort(String [] array) {

   String temp = null;

   for(int j=0;j<array.length;j++)

  {

 for(int i = 0; i<array.length-1;i++)

  {

  if(array[i].compareTo(array[i+1])<0)

  {

  temp = array[i];

  array[i] = array[i+1];

  array[i+1] = temp;

 }

 }

    } } }

Comments

0

The problem is that arrays are fixed size in memory and you can't drop the duplicated values from the array.

So either you transfer the duplicated values to unwanted values (like zeros or any string), or you use an ArrayList, which allows you to drop values from the list (because lists are not fixed size and you can change it).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.