简体   繁体   English

打印数组的元素而不重复元素

[英]Printing elements of an array without repeating an element

I have a java class which involves a String array and two for loops 我有一个java类,它涉及一个String数组和两个for循环

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 请问有没有使用.util。*包的解决方案

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;

           }

           }}}}

Add the Strings to Set<String> , which eliminates duplicate values, and then print them: 将字符串添加到Set<String> ,这将消除重复值,然后打印它们:

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

for(String s : set)
  System.out.println(s);

Use Map<String, Integer> , String for the input string, Integer for the noOftimesRepeated counter. 使用Map<String, Integer> ,String作为输入字符串,使用Integer作为noOftimesRepeated计数器。

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);

If you absolutely don't want to use java.util , you can still sort by hand and remove adjacent duplicates : 如果您绝对不想使用java.util ,您仍然可以手动排序并删除相邻的重复项:

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;
      }
    }
  }
}
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] 输出: [Khaled, Valderama, Rasheed, Daoud]

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()));

You can use set . 你可以使用set Set will avoid adding duplicates. Set将避免添加重复项。

    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. 如果您不想使用java.util.*包,请尝试以下方法。

  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++;
        }
    }

Aside from using Set , you can also create a list of unique items. 除了使用Set ,您还可以创建唯一项列表。

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- 不确定为什么你不想使用util包,但是 -

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);
}

You dun need 2 for loop to do it. 你需要2个循环才能完成它。 Just this 3 line of code will do! 只需这3行代码即可! :D :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 如果没有* ulit包

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! 
} 
}

try this. 试试这个。 The for Loop will not be running fully for duplicate items 对于重复项,for循环不会完全运行

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);

          }
     }
}

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. 我同意以前的人,首先你应该按顺序让你成为arraylist,你可以尝试Quicksort算法,其次你应该将当前元素与前一个元素进行比较,如果它们相等,则不要打印它。 it is easy, right? 这很容易,对吗?

you can extract your quicksort algorithm function to a util class, so you can use it in later development. 您可以将快速排序算法函数提取到util类,以便在以后的开发中使用它。

I found the solution,(The following solution doesn't involve java.util 我找到了解决方案,(以下解决方案不涉及java.util

package , and it depends on Quicksort Algorithm). 包,它取决于Quicksort算法)。

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;

 }

 }

    } } }

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). 因此,要么将重复的值传输到不需要的值(如零或任何字符串),要么使用ArrayList ,它允许您从列表中删除值(因为列表不是固定大小,您可以更改它)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM