不重复打印数组元素

4
我有一个涉及字符串数组和两个for循环的Java类。这个类遍历数组元素并打印它们以及它们在数组中的重复次数。我想要有人帮助我只打印每个元素(字符串)一次,即使它在数组中重复出现。下面的代码会多次打印数组中的某些元素,因此需要比较数组元素。
 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);

  }

 }

请问是否有不使用.util.*包的解决方案?

我有第二种尝试,但它只输出了一个元素并且存在冗余。

仅此而已。

 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;

           }

           }}}}

我已经给两个答案点了赞。如果你只需要去除重复项,使用arjacsoh的解决方案。如果你需要计算每个字符串出现的次数,使用lulyon的解决方案。 - Arnaud Denoyelle
请问有没有不使用 .util.* 包的解决方案? - PHPFan
有没有绝对避免使用 java.util.* 包的要求?我看到一些解决方案没有使用它(手动排序?),但它几乎等同于 java.util 中公开的方法,而且很可能会出现错误。 - Arnaud Denoyelle
需要绝对避免使用java.util.*包吗?是的,确切如此。 - PHPFan
12个回答

3

将字符串添加到Set<String>中,该集合会自动去重,然后将它们打印出来:

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

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

2

使用 Map<String, Integer>,其中String表示输入字符串,Integer表示noOftimesRepeated计数器。

示例:

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

请问有没有不使用 .util.* 包的解决方案? - PHPFan
@ElhadiMamoun 我有一种更加手动的方法(当然需要更多的代码),先对数组进行排序,然后计算相邻字符串。但时间复杂度为o(nlogn),比两个嵌套的for循环(o(n^2))要好。 - lulyon
@Ruchira 谢谢。这里的代码不完整,只是一个例子。 - lulyon
@lulyon,你的新手动方法避免了使用java.util.*包吗? - PHPFan
@ElhadiMamoun 可能是这样。第一步是排序,可以使用快速排序算法手动实现。第二步(通过对字符串数组进行一次遍历来计算相邻字符串的数量)本身就避免了使用Java包。 - lulyon
@ElhadiMamoun 这里是快速排序的代码 http://www.algolist.net/Algorithms/Sorting/Quicksort - lulyon

1
如果您绝对不想使用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;
      }
    }
  }
}

你的代码很好,不会重复显示元素,但它没有计算字符串重复出现的次数。 - PHPFan
1
你有一个已排序的数组。计算相邻元素出现次数并不是很困难。 - Arnaud Denoyelle
公共静态无返回值的主函数(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; }` 我对你的代码进行了一些修改,现在这段代码只能打印出一个元素的冗余次数,请问你还需要什么指导吗? - PHPFan

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

输出:[Khaled,Valderama,Rasheed,Daoud]

0

你可以按照以下方式操作:

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

0
你可以使用 setSet 可以避免添加重复项。
    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);

如果您不想使用 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++;
        }
    }

请问有没有不使用 .util.* 包的解决方案? - PHPFan
@ElhadiMamoun 你可以尝试我的第二种方法。 - Ruchira Gayan Ranaweera
但你的代码涉及到 Java.util 包中的数组类。 - PHPFan

0

除了使用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);
}

编辑 基于评论:

不确定为什么您不想使用 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);
}

请问有没有不使用 .util.* 包的解决方案? - PHPFan

0

你不需要使用两个for循环来完成它。只需这3行代码就可以了!: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);

如果没有ulit包

你将需要一个自定义排序方法。 伪代码可以像这样(不是一个高效的方法)

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

请问有没有不使用 .util.* 包的解决方案? - PHPFan
@ElhadiMamoun 是的,您需要自定义排序方法。伪代码可以像这样:“给定”lst数组; Array temp = new Array(lst.length);//两个for循环 for (i = 0; i < lst.length; i++) { if(i==0){ temp[i] = lst[i]; // 第一个数组 } for (u = 0 ; u < lst.length; u ++){ //在这里编写代码,如果lst[i]字符串不等于任何temp[u]字符串,则将它添加到内部。否则不用理会:)干杯! }} - Marcia Ong

0

试试这个。对于重复的项目,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);

          }
     }
}

请问有没有不使用 .util.* 包的解决方案? - PHPFan

0
我找到了解决方案,(以下解决方案不涉及java.util包,而是依赖于快速排序算法)。
谢谢大家。
     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;

 }

 }

    } } }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接