Finding Duplicates in Array and printing them only Once

前端 未结 6 1241

I am trying to loop through my array and find all the numbers that are repeating more than once:

E.G: if there is 1 1 2 3 4

It should print saying \

6条回答
  •  误落风尘
    2021-01-21 23:44

    Using the apache commons CollectionUtils.getCardinalityMap(collection):

      final Integer[] buffer = {1, 2, 3, 4, 5, 6, 7, 2, 1, 7, 9, 1, 1, 3};
      final List list = Arrays.asList(buffer);
      final Map cardinalityMap = CollectionUtils.getCardinalityMap(list);
      for (final Map.Entry entry: cardinalityMap.entrySet()) {
        if (entry.getValue() > 1) {
          System.out.println(entry.getKey());
        }
      }
    

    toString() of cardinalityMap looks like this after the init:

    {1=4, 2=2, 3=2, 4=1, 5=1, 6=1, 7=2, 9=1}
    

    Using standard java:

      final Integer[] buffer = {1, 2, 3, 4, 5, 6, 7, 2, 1, 7, 9, 1, 1, 3};
      final List list = Arrays.asList(buffer);
      final Set set = new LinkedHashSet(list);
      for (final Integer element: set) {
        if (Collections.frequency(list, element) > 1) {
          System.out.println(element);
        }
      }
    

提交回复
热议问题