Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java- going through an array and counting up with same values

Tags:

java

Im trying to understand how I can go through an array, and check if there are multiple generated values of the same string, and if they are, add them up to the counter. For example with this code i want to check if items[0] is equal to items[1], and if so counter++. Any advice would be appreciated.

 String[] items = {"apple", "pear", "lemon", "bread"};

 public int countUp() {
        int count = 0;
        int number = 0;
        for (int i = 1; i <items.length; i++) {
            while (number < items.length) {
                if (faces[number].equals(items[i])) {
                    count++;
                }
                number++;
            }
        return count;
    }
like image 446
Dante Avatar asked Dec 12 '25 03:12

Dante


2 Answers

 String[] items = {"apple","apple", "pear", "lemon", "bread", "pear"};

 Set<String> itemSet = new HashSet<>(Arrays.asList(items));
 int duplicates = items.length - itemSet.size();  // --> 2

HashSet will not add an element if it's already present. From Set one can read:

A collection that contains no duplicate elements. More formally, sets contain no pair of elements e1 and e2 such that e1.equals(e2), and at most one null element. As implied by its name, this interface models the mathematical set abstraction.

So just check their size difference and you'll get the number of duplicates.

like image 172
aran Avatar answered Dec 14 '25 21:12

aran


One mistake in your logic is that you're not resetting the value of number after every for loop iteration.

Your program would only calculate the number of duplicates the first element has. Though brute force is not the optimal way to solve this, I just pointed out the bug.

public int countUp() {
    int count = 0;
    int number = 0;
    for (int i = 0; i <items.length; i++) {
        number = i + 1;             // Add this line
        while (number < items.length) {
            if (items[number].equals(items[i])) {
                count++;
            }
            number++;
        }
    return count;
}
like image 28
Major_Ash Avatar answered Dec 14 '25 21:12

Major_Ash



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!