Sydney Ballard
Sydney Ballard

Reputation: 25

Counting occurrence of char in array of string

I'm writing a Java program that counts the appearance of a particular char (nuc) within a string (nucleotide sequence) within an array (list of nucleotide sequences). It's meant to return the string with the most appearances of the character.

input: list of strings (ex. {"aaagt","cgaat","ttt"} ), char = "a" / output: "aaagt" (since most appearances of "a")

Below, I have the Python version I wrote. How would I translate this to Java?

def DNAMaxNucleiotide(listStrings, nuc):
    nucCount = 0
    SEQ = ''

    for seq in listStrings:
        newCount = 0
        splitSeq = list(seq)
        for char in splitSeq:
            if char == nuc:
                newCount += 1
        if newCount > nucCount:
            nucCount = newCount
            SEQ = seq
        else:
            pass


    return SEQ

Thanks!

Upvotes: 0

Views: 87

Answers (1)

Andreas
Andreas

Reputation: 159215

Here is one way of doing it, in Java 8+:

static String dnaMaxNucleiotide(int codePoint, String... listStrings) {
    return Stream.of(listStrings)
            .max(Comparator.comparingLong(s -> countChar(codePoint, s)))
            .orElse("");
}
private static long countChar(int codePoint, String s) {
    return s.codePoints()
            .filter(cp -> cp == codePoint)
            .count();
}

Test

System.out.println(dnaMaxNucleiotide('a', "aaagt","cgaat","ttt"));

Output

aaagt

Upvotes: 1

Related Questions