【问题标题】:How to generate an error if a number appears more than once in a list如果一个数字在列表中出现多次,如何生成错误
【发布时间】:2020-01-20 20:49:34
【问题描述】:

我有一个列表[0, 0, 1, 0, 1, 2, 0, 2, 3],我想找到一种方法来在列表中重复某个数字时生成错误。

所以,我知道Collections.frequency 可以计算一个数字在列表中出现的次数。

if (Collections.frequency((Collection<?>) smallerLists.toArray()[0], ((ArrayList<Integer>) smallerLists.toArray()[0]).get(0)) > 1) ;
System.out.println("ERREUR : Le nombre " + ((ArrayList<Integer>) smallerLists.toArray()[0]).get(0) + " apparaît plus d'une fois sur la ligne 1");
if (Collections.frequency((Collection<?>) smallerLists.toArray()[0], ((ArrayList<Integer>) smallerLists.toArray()[0]).get(1)) > 1) ;
System.out.println("ERREUR : Le nombre " + ((ArrayList<Integer>) smallerLists.toArray()[0]).get(1) + " apparaît plus d'une fois sur la ligne 1");
if (Collections.frequency((Collection<?>) smallerLists.toArray()[0], ((ArrayList<Integer>) smallerLists.toArray()[0]).get(2)) > 1) ;
System.out.println("ERREUR : Le nombre " + ((ArrayList<Integer>) smallerLists.toArray()[0]).get(2) + " apparaît plus d'une fois sur la ligne 1");
if (Collections.frequency((Collection<?>) smallerLists.toArray()[0], ((ArrayList<Integer>) smallerLists.toArray()[0]).get(3)) > 1) ;
System.out.println("ERREUR : Le nombre " + ((ArrayList<Integer>) smallerLists.toArray()[0]).get(3) + " apparaît plus d'une fois sur la ligne 1");
if (Collections.frequency((Collection<?>) smallerLists.toArray()[0], ((ArrayList<Integer>) smallerLists.toArray()[0]).get(4)) > 1) ;
System.out.println("ERREUR : Le nombre " + ((ArrayList<Integer>) smallerLists.toArray()[0]).get(4) + " apparaît plus d'une fois sur la ligne 1");
if (Collections.frequency((Collection<?>) smallerLists.toArray()[0], ((ArrayList<Integer>) smallerLists.toArray()[0]).get(5)) > 1) ;
System.out.println("ERREUR : Le nombre " + ((ArrayList<Integer>) smallerLists.toArray()[0]).get(5) + " apparaît plus d'une fois sur la ligne 1");
if (Collections.frequency((Collection<?>) smallerLists.toArray()[0], ((ArrayList<Integer>) smallerLists.toArray()[0]).get(6)) > 1) ;
System.out.println("ERREUR : Le nombre " + ((ArrayList<Integer>) smallerLists.toArray()[0]).get(6) + " apparaît plus d'une fois sur la ligne 1");
if (Collections.frequency((Collection<?>) smallerLists.toArray()[0], ((ArrayList<Integer>) smallerLists.toArray()[0]).get(7)) > 1) ;
System.out.println("ERREUR : Le nombre " + ((ArrayList<Integer>) smallerLists.toArray()[0]).get(7) + " apparaît plus d'une fois sur la ligne 1");
if (Collections.frequency((Collection<?>) smallerLists.toArray()[0], ((ArrayList<Integer>) smallerLists.toArray()[0]).get(8)) > 1) ;
System.out.println("ERREUR : Le nombre " + ((ArrayList<Integer>) smallerLists.toArray()[0]).get(8) + " apparaît plus d'une fois sur la ligne 1");

我知道这段代码很繁重,而且我确信有一种更简单的方法(也许是迭代?我在编程方面还是很陌生)。更简单的方法是通过创建构造函数来生成异常,但我被卡住了.. 谢谢!

【问题讨论】:

  • 这能回答你的问题吗? Java 8, Streams to find the duplicate elements
  • 所以你有一个列表集合?为什么不将smallerLists.toArray()[0] 提取到正确类型的局部变量中,而不是将其与类型转换一起重复 27 次?顺便说一句,smallerLists.iterator().next() 比将整个集合转储到数组中更有效,只是为了获取第一个元素。并且检查重复项就像if(new HashSet&lt;&gt;(collection) .size() != collection.size()) System.out.println("there are duplicates"); 一样简单...

标签: java collections error-handling repeat generate


【解决方案1】:

我会说使用Collectors.groupingByCollectors.counting() 来收集Map 中的计数值

Map<String, Long> valueWithCount = list.stream()
        .collect(Collectors.groupingBy(Function.identity(),Collectors.counting()));

然后流式传输Map 以查找计数大于 1 的任何值

boolean result = valueWithCount.entrySet()
                               .stream()
                               .anyMatch(i->i.getKey().equals(10) && i.getValue()>1);

您可以将两者合并为一个操作

boolean result = list.stream().collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
            .entrySet().stream().anyMatch(i -> i.getKey().equals(10) && i.getValue() > 1);

【讨论】:

    【解决方案2】:

    您可以使用 Identify duplicates in a List 等已提问问题中建议的解决方案之一找到重复项。

    然后,如果找到重复项,您可以将结果传递给您构建消息的异常构造函数。然后抛出你的异常。

    【讨论】:

      【解决方案3】:

      您可以通过回调处理欺骗行为,而不是抛出异常。这样您就可以处理列表中的多个异常。下面的解决方案使用一个带有支持 TreeMap 的新类以及一个回调来处理传递给构造函数的原始数组中的重复项或使用 addItem 方法添加的其他项。

      代码产生以下输出:

      Constructor: 
      We have a dupe: 0 which has occurred 2 times so far
      We have a dupe: 0 which has occurred 3 times so far
      We have a dupe: 1 which has occurred 2 times so far
      We have a dupe: 0 which has occurred 4 times so far
      We have a dupe: 2 which has occurred 2 times so far
      
      Add new items: 
      Duplicate 4 has had 2 occurrences
      
      Frequency List
          0 appears 4 times
          1 appears 2 times
          2 appears 2 times
          3 appears 1 times
          4 appears 2 times
      
      

      请注意,addItem 和构造函数被重载以处理 null 回调,并且对 addItem 的第二次调用传入一个 Lambda 表达式作为回调。

      import java.util.Set;
      import java.util.TreeMap;
      
      interface DupeHandler{
          public void handleDupe(Integer dupValue, Integer dupCount);
      }
      
      class FrequencyList {
          private TreeMap<Integer, Integer> _tm = new TreeMap<Integer, Integer>();
      
          public FrequencyList(int[] array){
              this(array, (DupeHandler)null);
          }
      
          public FrequencyList(int[] array, DupeHandler m){
              for(var i : array){
                  addItem(i,m);
              }
          }
      
          public void addItem(Integer i){
              addItem(i, null);
          }
      
          public void addItem(Integer key, DupeHandler m){
              Integer count = _tm.get(key);
              if(count==null){
                  _tm.put(key, Integer.valueOf(1));
              } else {
                  Integer newCount = (Integer.valueOf(count+1));
                  _tm.put(key, newCount);
                  if(m!=null){
                      m.handleDupe(key, newCount);
                  }
              }
          }
      
          public Set<Integer> getUniqueValues(){
              return _tm.keySet();
          }
      
          @Override
          public String toString() {
              StringBuilder sb=new StringBuilder();
              sb.append("\nFrequency List\n");
              for(var k:_tm.keySet()){
                  sb.append("\t" + k.toString() + " appears " + _tm.get(k).toString()+ " times\n");
              }
              return sb.toString();
          }
      }
      
      public class FrequencyListTest implements DupeHandler{
          public static void main(String[] args) {
              int[] intArray = new int[] {0,0,1,0,1,2,0,2,3};
              FrequencyListTest flt = new FrequencyListTest();
      
              System.out.println("Constructor: ");
              FrequencyList fl = new FrequencyList(intArray, flt);
      
              System.out.println("\nAdd new items: ");
              fl.addItem(4,flt);
              // callback can also be passed in as a lambda expression
              fl.addItem(4,(n,c)-> 
                  System.out.println("Duplicate " + n + " has had " + c + " occurrences"));
      
              System.out.println(fl);
      
          }
      
          @Override
          public void handleDupe(Integer dupValue, Integer dupCount) {
              System.out.println("We have a dupe: " + dupValue + " which has occurred " + dupCount + " times so far");
          }
      }
      
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-03-13
        • 1970-01-01
        • 1970-01-01
        • 2021-08-26
        • 1970-01-01
        • 2021-04-03
        相关资源
        最近更新 更多