简体   繁体   English

如何计算字符串出现的次数

[英]How To Count The Number of Times a String Occurs

So I have created an error message for my code. 因此,我为代码创建了一条错误消息。 Currently, my code spits out the error message each time it appears. 当前,我的代码每次出现时都会弹出错误消息。 My code validates and makes sure that an excel file is formatted correctly. 我的代码验证并确保Excel文件格式正确。 After validation, it gives back error/warning messages if they occur. 验证后,它会返回错误/警告消息(如果发生)。 So when I get error messages, each message appears each time it happens. 因此,当我收到错误消息时,每条消息都会在每次发生时出现。 For example, the error message "Error, id must not contain special characters" happens 6 times when validating the excel file. 例如,验证Excel文件时,会出现6次错误消息“错误,ID不能包含特殊字符”。 What way is there to simply write to check if the message already occurred, and keep a counter of how many times so I can display that? 有什么方法可以简单地写检查消息是否已经发生,并记下多少次以便显示出来?

I thought about something like if (message = message) { //then create counter} but that doesn't work since message always equals message. 我想到了类似if (message = message) { //then create counter}但是由于message始终等于message,因此无法正常工作。 Does anyone have any ways to do it? 有人有办法吗?

EDIT: Here is a snipit of the code for validation. 编辑:这是验证的代码。 I want to group the messages together and not have them repeat when posting to the API. 我想将消息分组在一起,并且在发布到API时不要重复它们。

        // if there are errors, then
        if (!errorResponse.getItems().isEmpty()) {

            // set error response
            Iterator<ErrorMessage> iter = errorResponse.getItems().iterator();

            Set<ErrorMessage> summarizedErrorMessages = new HashSet<>();

            while (iter.hasNext()) {
                ErrorMessage sem = new ErrorMessage();
                ErrorMessage em = iter.next();
                if (!summarizedErrorMessages.contains(em)) {
                    sem.setMessage(em.getMessage());
                    sem.setTotal(1);
                } else {
                    sem.setTotal(sem.getTotal() + 1);
                }
                summarizedErrorMessages.add(sem);
            }
            errorResponse.setItems(summarizedErrorMessages);
            warningResponse.setItems(new ArrayList<WarningMessage>());

A HashMap<String,Integer> will use a String 's hash code for the key, so the same String will map to the same location in the map. HashMap<String,Integer>将使用String的哈希码作为键,因此相同的String将映射到地图中的相同位置。

So, you can just push your message strings into the map with the count of 1 when you first see it (when it's not in the map), and then increment it thereafter: 因此,您可以在第一次看到消息字符串时(当它不在地图中时)将计数为1的消息字符串推入地图,然后再将其递增:

HashMap<String,Integer> messageCounts = new HashMap<>();
messages.forEach( message -> {
    messageCounts.putIfAbsent( message, 0 );
    messageCounts.computeIfPresent( message, (k,v) -> v+1 );
});

So, for your specific case it might be something like this: 因此,对于您的特定情况,可能是这样的:

// First map messages to counts
HashMap<String,Integer> messageCounts = new HashMap<>();
errorResponse.getItems().forEach( errorMessage -> {
    messageCounts.putIfAbsent( errorMessage.getMessage(), 0 );
    messageCounts.computeIfPresent( errorMessage.getMessage(), (k,v) -> v+1 );
});

// Then create the summary objects
List<ErrorMessages> summaries = 
    messageCounts.entrySet().stream().map( e -> {
        ErrorMessage summary = new ErrorMessage();
        summary.setMessage( e.getKey() );
        summary.setTotal( e.getValue() );
        return summary;
    } ).collect( Collectors.toList() );

errorResponse.setItems( summaries );

Use a HashMap<String, Long> where the key is the error message and the value is the number of times the error occured. 使用HashMap<String, Long> ,其中键是错误消息,值是错误发生的次数。

When receiving an error message, check if map.containsKey(message) , then get the counter ( long counter = map.get(message) ), increment it and put it back in the map ( map.put(message, counter + 1L) ). 收到错误消息时,请检查if map.containsKey(message) ,然后获取计数器( long counter = map.get(message) ),对其进行递增,然后将其放回地图中( map.put(message, counter + 1L) )。

If the map does not contain the message, add it to the map and initialize the counter to 1 ( map.put(message, 1L) ). 如果该映射不包含该消息,则将其添加到该映射并将计数器初始化为1( map.put(message, 1L) )。

Something like this : 像这样的东西:

private Map<String, Long> errors = new HashMap<String, Long>();

public void handleError(String error) {
    if(errors.containsKey(error)) {
        Long counter = errors.get(error);
        errors.put(error, counter + 1L);
    } else {
        errors.put(error, 1L);
    }
}

Test : 测试

handleError("Error, id must not contain special characters");
handleError("StackOverflow");
handleError("Error, id must not contain special characters");
handleError("Error, id must not contain special characters");
handleError("StackOverflow");

for (Map.Entry<String, Long> entry : errors.entrySet()) {
    System.out.println(entry.getKey() + " : " + entry.getValue());
}

Output : 输出

StackOverflow : 2
Error, id must not contain special characters : 3

Just creating a seperate answer here so I can post the full code that worked for this question. 只需在此处创建一个单独的答案,这样我就可以发布适用于该问题的完整代码。 Here is the code that worked with no errors: 这是没有错误的代码:

            // if there are errors, then
        if (!errorResponse.getItems().isEmpty()) {

            // set error response
            Iterator<ErrorMessage> iter = errorResponse.getItems().iterator();

            HashMap<String, Integer> messageCounts = new HashMap<String, Integer>();
            errorResponse.getItems().forEach(ErrorMessage -> {
                messageCounts.putIfAbsent(ErrorMessage.getMessage(), 1);
                messageCounts.computeIfPresent(ErrorMessage.getMessage(), (k, v) -> v + 1);
            });

            Set<ErrorMessage> summaries = new HashSet<>();
            for (String s : messageCounts.keySet()) {
                ErrorMessage summary = new ErrorMessage();
                summary.setMessage(s);
                summary.setTotal(messageCounts.get(s));
                summaries.add(summary);
            }

            errorResponse.setItems(summaries);
            warningResponse.setItems(new ArrayList<WarningMessage>());

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

相关问题 一个数字出现多少次 - How many times a number occurs 我如何计算一个项目在给定日期在mysql中发生的次数 - How can I count the number of times an item occurs in a given date in mysql 如何在不使用s循环的情况下计算字符多次出现在字符串中 - how to count many times a character occurs in a string without using s loop 在不使用映射的情况下如何计算字符串出现在数组中的次数? - How to count the number of times a string appears in an array without using maps? 查找字符串中连续和非连续表达式的次数 - Finding the Number of Times an Expression Occurs in a String Continuously and Non Continuously 在不使用库的情况下计算字符串中字母出现的次数 - Counting number of times a letter occurs in a string without using libraries 如何处理一些事件发生多少次的计数? - How to handle count of how many times some events occurs? 计算aaa在具有和重叠的字符串中出现的次数 - count number of times aaa appears in a string with and with overlaping 如何查找Java中的数组列表中特定元素出现的次数 - How to find the number of times a specific element occurs in an Array list in Java 我需要计算使用扫描仪和JFIleChooser在文件中出现子字符串的次数 - I need to count the number of times a substring occurs in a file using scanner and JFIleChooser
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM