【问题标题】:How to get unique values from array如何从数组中获取唯一值
【发布时间】:2012-12-10 07:52:56
【问题描述】:

我有一个数组,我想从中删除重复项。

for(int data1=startpos;data1<=lastrow;data1++) {
    String movie_soundtrk=cells.getCell(data1,Mmovie_sndtrk_cl).getValue().toString();
    al.add(movie_soundtrk);
}

String commaSeparated=al.toString();
String [] items = commaSeparated.split(",");
String[] trimmedArray = new String[items.length];
for (int i = 0; i < items.length; i++) {
    trimmedArray[i] = items[i].trim();
}

Set<String> set = new HashSet<String>();
Collections.addAll(set, trimmedArray);

System.out.println(set);

但这并没有给我数组中的唯一值。

我的数组:- {English, French, Japanese, Russian, Chinese Subtitles,English, French, Japanese, Russian, Chinese Subtitles}

Out Put :- [日文、俄文、法文、中文字幕]、中文字幕、[英文、英文]

【问题讨论】:

  • 我没有反对票和接近票。艰难的夜晚。
  • array.tostring 包含 [] 和我的第一项像成为 [english, and last Chinese Subtitles] 那为什么给我错误的输出如何避免来自 array.tostring() 的方括号
  • 获取array.toString()的子串去掉方括号
  • 这是一个很老的问题。你加入接受答案吗?

标签: java arrays


【解决方案1】:

你可以在java 7中一行完成:

String[] unique = new HashSet<String>(Arrays.asList(array)).toArray(new String[0]);

在 java 8 中更短更简单:

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

【讨论】:

  • 如果类型是原始数组,则这不起作用,例如,如果上面的“array”是一个 byte[][] 数组(并且 Arrays.asList 的结果是一个 List ),我不确定在这种情况下如何使用 Stream.distinct。
  • @alex 你不能使用这个或JDK中的任何东西来查找唯一数组,因为javs数组不是Comparable;它们都是独一无二的,即使它们的内容相同。您必须实现自己的代码才能完成这项工作,或者使用List&lt;List&lt;Byte&gt;&gt; 而不是byte[][],因为列表 Comparable(它们比较它们的元素)。
  • Comparabledistinct() 无关,因为它使用equals() 方法检查相同的对象。文档摘录:Returns a stream consisting of the distinct elements (according to Object.equals(Object)) of this stream.
  • 我想知道这个解决方案的时间复杂度是多少。你能解释一下吗?
  • @Liu 时间复杂度为 O(n),其中 n 是字符串长度,因为 HashSet(支持 Stream 的 distinct())上的所有操作都是恒定时间(即 O(1))并且有 n 个操作 - 每个字符 1 个。
【解决方案2】:

HashSet 将完成这项工作。

你可以试试这个:

List<String> newList = new ArrayList<String>(new HashSet<String>(oldList));

【讨论】:

    【解决方案3】:

    如果您不想使用 Hashset 或上面提到的 Java8 中的新方法,您可以编写此代码,您只需首先对数组进行排序,以便相似的值将彼此相邻,然后计算不同对的数量在相邻的单元格中。

        public static int solution(int[] A) {
        int count = 1;
        Arrays.sort(A);
        for (int i = 1; i < A.length - 1; i++) {
            if (A[i] != A[i + 1]) {
                count++;
            }
        }
        return count;
    }
    

    【讨论】:

      【解决方案4】:

      使用 Java 8 的 Stream API,这是一个具有通用 Array 类型的解决方案:

      public static <T> T[] makeUnique(T... values)
      {
          return Arrays.stream(values).distinct().toArray(new IntFunction<T[]>()
          {
      
              @Override
              public T[] apply(int length)
              {
                  return (T[]) Array.newInstance(values.getClass().getComponentType(), length);
              }
      
          });
      }
      

      它适用于任何 Object 类型的数组,但不适用于原始数组。

      对于原始数组,它看起来像这样:

      public static int[] makeUnique(int... values)
      {
          return Arrays.stream(values).distinct().toArray();
      }
      

      最后是一个小单元测试:

      @Test
      public void testMakeUnique()
      {
          assertArrayEquals(new String[] { "a", "b", "c" }, makeUnique("a", "b", "c", "b", "a"));
          assertArrayEquals(new Object[] { "a", "b", "c" }, makeUnique(new Object[] { "a", "b", "c", "b", "a" }));
          assertArrayEquals(new Integer[] { 1, 2, 3, 4, 5 }, makeUnique(new Integer[] { 1, 2, 2, 3, 3, 3, 1, 4, 5, 5, 5, 1 }));
          assertArrayEquals(new int[] { 1, 2, 3, 4, 5 }, makeUnique(new int[] { 1, 2, 2, 3, 3, 3, 1, 4, 5, 5, 5, 1 }));
      }
      

      【讨论】:

        【解决方案5】:

        你可以得到两套,一套有所有的字幕,另一套有重复的

        String[] trimmedArray = new String[items.length];
        Set<String> subtitles = new HashSet<String>();
        Set<String> duplicatedSubtitles = new HashSet<String>();
        
        foreach(String subtitle : trimmedArray){
            subtitle = subtitle.trim();
            if(subtitles.contains(subtitle)){
                duplicatedSubtitles.add(subtitle);
            }
            subtitles.add(subtitle);
        }
        

        【讨论】:

          【解决方案6】:

          试试这个

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

          调用它

          set.addAll(trimmedArray);
          

          【讨论】:

            【解决方案7】:

            为什么要先将项目添加到数组中,然后再将其转换为字符串?只需遍历数组并将它们复制到 Set。然后打印新创建的包含唯一值的集合。

            Set<String> set = new HashSet<String>();
            for (int i = 0; i < al.length; i++) {
                set.add(al[i]);
            }
            
            for (String str : set) {
                System.out.println(str);
            }
            

            【讨论】:

            • This is Giving me Out put as Japanese Russian French Chinese Subtitles] Chinese Subtitles [English English It should be only Japanese Russian French Chinese Subtitles English
            • 如果你的数组包含你写的值,那么这段代码可以按预期工作。我认为你的数组有问题。再次检查您的数组。确保它包含字符串值。
            【解决方案8】:

            此代码将从数组中计算不同的元素,然后找到它们的出现。并计算百分比并将其保存到hashmap。

            int _occurrence = 0;
                    String[] _fruits = new String[] {"apple","apple","banana","mango","orange","orange","mango","mango","banana","banana","banana","banana","banana"};
                    List<String> _initialList = Arrays.asList(_fruits);
                    Set<String> treesetList = new TreeSet<String>(_initialList);
                    String[] _distinct =  (String[]) treesetList.toArray(new String[0]);
            
                    HashMap<String,String> _map = new HashMap<String,String>();
                    int _totalElement = _fruits.length;
                    for(int x=0;x<_distinct.length;x++){
                        for(int i=0;i<_fruits.length;i++){
                            if(_distinct[x].equals(_fruits[i])){
                                ++_occurrence;
                            }
                        }
                        double _calPercentage = Math.round((((double)_occurrence/(double)_totalElement)*100));
                        _map.put(_distinct[x], String.valueOf(_calPercentage+"%"));
                        _occurrence = 0;
                    }
                    System.out.println(_map);
            

            【讨论】:

              【解决方案9】:

              让我们看看如何从数组中找到不同的值。

                public class Distinct  {
                      public static void main(String args[]) {
                           int num[]={1,4,3,2,6,7,4,2,1,2,8,6,7};
                              for(int i=0; i<num.length; i++){
                                  boolean isdistinct = true;
                                  for(int j=0; j<i; j++){
                                      if(num[i] == num[j]){
                                          isdistinct =false;
                                          break;
                                      }
                                 }
                                  if(isdistinct){
                                      System.out.print(num[i]+" ");
                                  }
                             }
                         }
                   }
              

              【讨论】:

                【解决方案10】:
                int arr[] = {1,1,2,2,3,3,4,5,5,6}; 
                for(int i=0; i<arr.length; i++) {
                int count = 0;
                    for(int j=0; j<arr.length; j++) {
                        if ((arr[i] == arr[j]) && (i!=j)) {
                            count++ ;
                        }
                    }
                        if(count==0) {
                            System.out.println(arr[i]);
                        }
                }
                

                【讨论】:

                • 以上解决方法无效,发帖前请检查。
                【解决方案11】:
                public static int[] findAndReturnUniqueIntArray(int[] arr) {
                    int[] distinctElements = {};
                    int newArrLength = distinctElements.length;
                    for (int i = 0; i < arr.length; i++) {
                        boolean exists = false;
                        if (distinctElements.length == 0) {
                            distinctElements = new int[1];
                            distinctElements[newArrLength] = arr[i];
                            newArrLength++;
                        }
                
                        else {
                            for (int j = 0; j < distinctElements.length; j++) {
                                if (arr[i] == distinctElements[j]) {
                                    exists = true;
                                    break;
                                }
                            }
                            if (exists == false) {
                                distinctElements = Arrays.copyOf(distinctElements, distinctElements.length+1);
                                distinctElements[distinctElements.length-1] = arr[i];
                                newArrLength++;
                                exists = false;
                            }
                        }
                    }
                    return distinctElements;
                }
                

                【讨论】:

                • 请解释你的答案,不要只是张贴代码
                【解决方案12】:

                如果你的数组满足这两个条件-:

                1. 只允许重复和单个值(不允许三次或更多)

                2. 数组中应该只有一个唯一值

                   // Use Bitwise 'exclusive or' operator to find unique value 
                   int result = array[0];
                   for (int i = 1; i < array.length; i++) {
                       result  ^= array[i];
                   }
                   System.out.println(result);
                  

                  } }

                【讨论】:

                  【解决方案13】:

                  在python中你可以使用Set。

                  s = Set()
                  data_list = [1,2,3,4]
                  s.update(data_list)
                  

                  【讨论】:

                    猜你喜欢
                    • 1970-01-01
                    • 1970-01-01
                    • 2019-10-20
                    • 2011-03-02
                    • 1970-01-01
                    • 2020-09-22
                    • 2019-01-03
                    • 1970-01-01
                    相关资源
                    最近更新 更多