简体   繁体   English

如果数字在列表中出现多次,如何生成错误

[英]How to generate an error if a number appears more than once in a list

I have a list [0, 0, 1, 0, 1, 2, 0, 2, 3] and I want to find a way to generate an error if a number is repeated in the list.我有一个列表[0, 0, 1, 0, 1, 2, 0, 2, 3]并且我想找到一种方法来在列表中重复一个数字时生成错误。

So, I know that Collections.frequency can count how many time a number is found in a list.所以,我知道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");

I know this code is heavy and I'm sure there's an easier way to do it (an iteration maybe? I'm still very new at programming).我知道这段代码很重,我相信有一种更简单的方法来做到这一点(也许是迭代?我对编程还是很陌生)。 The easier way would be to generate an exception by making a constructor but I'm stuck.. Thanks !更简单的方法是通过创建构造函数来生成异常,但我被卡住了..谢谢!

I would say to use Collectors.groupingBy with Collectors.counting() to collect the value with count in Map我会说使用Collectors.groupingByCollectors.counting()来收集Map计数值

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

And then stream the Map to find any value with count greater than 1然后流式传输Map以查找计数大于 1 的任何值

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

You can combine both into one operation您可以将两者合并为一项操作

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

You can find the duplicates by using one of the solutions suggested in already asked questions like Identify duplicates in a List .您可以使用已问过的问题(例如识别列表中的重复项)中建议的解决方案之一来查找重复

Then, if a duplicate is found, you could pass the result to your exception constructor where you build your message.然后,如果找到重复项,您可以将结果传递给您构建消息的异常构造函数。 Then throw your exception.然后抛出你的异常。

Rather than throwing an exception you could handle dupes with a callback.您可以使用回调处理欺骗,而不是抛出异常。 This way you could deal with multiple exceptions in a list.这样您就可以处理列表中的多个异常。 The solution below uses a new class with a backing TreeMap along with a callback to handle duplicates either in the original array passed into the constructor or for additional items added with the addItem method.下面的解决方案使用一个带有支持 TreeMap 的新类以及一个回调来处理传递给构造函数的原始数组或使用 addItem 方法添加的其他项中的重复项。

The code produces the following output:该代码产生以下输出:

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

Note that addItem and the constructor are overloaded to handle a null callback and that the second call to addItem passes in a Lambda expression as the callback.请注意,addItem 和构造函数被重载以处理空回调,并且对 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");
    }
}

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

相关问题 如何获取在字符串列表中出现多次的单词的索引 - How to grab the indexes of a word that appears more than once in a list of Strings 警告不止一次出现 - warning appears more than once 如果列表中出现多次,则删除该项目的所有实例 - Remove all instances of an item in a list if it appears more than once 如果单词出现不止一次,如何在字符串数组中列出单词的两个索引? - How can I list both indexes of a word in a string array if the word appears more than once? 如果相同的字符出现多次,如何获取字符数组并返回true - How to take an array of chars and return true if the same character appears more than once 如何在处理中一次渲染列表中的多个对象? - How to render more than 1 object in list at once in Processing? 删除链表中出现多次的每个元素的第一次出现 - Removes the first occurrence of every element that appears more than once in the linkedlist 如何迭代比Java中列表大小指定的次数更多的次数 - how to iterate more number of times than size specified of list in java 如何在Java中获取HashMap的相同值多次出现次数? - how can i get the number of same-value-more-than-once occurrences for a HashMap in Java? 如何查找没有出现多次的数字(1987年至2013年的J3 CCC 2013) - How to find a number with no digit occurring more than once (J3 CCC 2013 from 1987 to 2013)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM