First Non Repeating Character using hashmap in one loop? - java

Recently an interviewer asked me to implement the first non repeating character in a string,I implemented it with hashmap using two different loops.Although the time complexity is O(n)+O(n),but he asked me to solve in a single loop.Can someone tells me how to do that?
Below is my implementation:
import java.util.HashMap;
import java.util.Map;
public class firstnonrepeating {
public static void main(String[] args) {
String non = "nnjkljklhihis";
Map<Character, Integer> m = new HashMap<Character, Integer>();
for (int i = 0; i < non.length(); i++) {
if (m.get(non.charAt(i)) != null) {
m.put(non.charAt(i), m.get(non.charAt(i)) + 1);
} else {
m.put(non.charAt(i), 1);
}
}
for (int i = 0; i < non.length(); i++) {
if (m.get(non.charAt(i)) == 1) {
System.out.println("First Non Reapeating Character is "
+ non.charAt(i));
break;
} else {
if (i == non.length() - 1)
System.out.println("No non repeating Character");
}
}
}
}

String non = "nnnjkljklhihis";
Map<String,LinkedHashSet<Character>> m = new HashMap<String,LinkedHashSet<Character>>() ;
m.put("one", new LinkedHashSet<Character>());
m.put("else", new LinkedHashSet<Character>());
m.put("all", new LinkedHashSet<Character>());
for (int i = 0; i < non.length(); i++) {
if (m.get("all").contains(non.charAt(i))) {
m.get("one").remove(non.charAt(i));
m.get("else").add(non.charAt(i));
} else {
m.get("one").add(non.charAt(i));
m.get("all").add(non.charAt(i));
}
}
if(m.get("one").size()>0){
System.out.println("first non repeatant : "+m.get("one").iterator().next());
}

Here is how I would do it:
import java.util.HashMap;
import java.util.Map;
public class Main
{
public static void main(String[] args)
{
String characters = "nnjkljklhihis";
Character firstNonRepeatingChar = getFirstNonRepeatingCharacter(characters);
if(firstNonRepeatingChar == null)
{
System.out.println("No non repeating characters in " + characters);
}
else
{
System.out.println("The first non repeating character is " + firstNonRepeatingChar);
}
}
private static Character getFirstNonRepeatingCharacter(String characters)
{
Map<Integer, Character> m = new HashMap<Integer, Character>();
for(int i = 0; i < characters.length(); i++)
{
Character currentChar = characters.charAt(i);
if(i > 0)
{
Character previousChar = m.get(i-1);
if(!previousChar.equals(currentChar))
{
return currentChar;
}
}
m.put(i, currentChar);
}
return null;//No non repeating character found
}
}

This is the same answer as Osama, re-written in a more modern way.
public static Optional<Character> getFirstNonRepeatingCharacter(String characters) {
HashMap<Character, Consumer<Character>> map = new HashMap<>();
LinkedHashSet<Character> set = new LinkedHashSet<>();
for(char c: characters.toCharArray()) {
map.merge(c, set::add, (_1, _2) -> set::remove).accept(c);
}
return set.stream().findFirst();
}

One more possible solution to this:
public class FirstNonRepeatingCharacterInString {
public static void main(String[] args) {
Character character = firstNonRepeatingCharacter("nnjkljklhihis");
System.out.println("First Non repeating character : " + character != null ? character : null);
}
private static Character firstNonRepeatingCharacter(String arg) {
char[] characters = arg.toCharArray();
Map<Character, Character> set = new LinkedHashMap<>();
// cost of the operation is O(n)
for (char c : characters) {
if (set.containsKey(c)) {
set.remove(c);
} else {
set.put(c, c);
}
}
//here we are just getting the first value from collection
// not iterating the whole collection and the cost of this operation is O(1)
Iterator<Character> iterator = set.keySet().iterator();
if (iterator.hasNext()) {
return iterator.next();
} else {
return null;
}
}
}

Given a string, find its first non-repeating character:
public class Test5 {
public static void main(String[] args) {
String a = "GiniSoudiptaGinaProtijayi";
Map<Character, Long> map = a.chars().mapToObj(
ch -> Character.valueOf((char)ch)
).collect(Collectors.groupingBy(Function.identity(),
LinkedHashMap:: new,
Collectors.counting()
));
System.out.println(map);
//List<Character> list = map.entrySet().stream().filter( entry -> entry.getValue() == 1 )
//.map(entry -> entry.getKey()).collect(Collectors.toList());
//System.out.println(list);
Character ch = map.entrySet().stream()
.filter( entry -> entry.getValue() == 1L )
.map(entry -> entry.getKey()).findFirst().get();
System.out.println(ch);
}
}

Related

Problems with sorting the characters of a word

I have a problem that I have been struggling with for some time.
I am given a word consisting of small or large letters of the English alphabet, to sort the characters so that in the first positions appear the characters that appear most often in the word, and if they appear by the same number of times, they will be sorted lexicographical.
Such as:
input:
Instructions
output:
iinnssttcoru
So far I have written this, but from here I do not know how to sort them and display properly, a tip?
public class Main {
public static void main(String[] args) throws IOException {
String testString = " ";
BufferedReader rd = new BufferedReader(new InputStreamReader(System.in));
testString = rd.readLine();
Map<Character, List<Character>> map = new HashMap<>();
for (int i = 0; i < testString.length(); i++) {
char someChar = testString.charAt(i);
if (someChar == ' ') {
continue;
}
char ch = testString.charAt(i);
List<Character> characters = map.getOrDefault(Character.toLowerCase(ch), new ArrayList<>());
characters.add(ch);
map.put(Character.toLowerCase(ch), characters);
}
List<Map.Entry<Character, List<Character>>> list = new ArrayList<>(map.entrySet());}
You can add TreeMap counterAppear with the key is the number of repetitions of the character and value is a list of characters has the same number of key repetitions. This list needs to be sorted before printing to ensure the order as required. Use TreeMap to make sure the map is sorted by key(the number of repetitions).
public static void main(String[] args) throws IOException {
String testString = " ";
BufferedReader rd = new BufferedReader(new InputStreamReader(System.in));
testString = rd.readLine();
Map<Character, List<Character>> map = new HashMap<>();
for (int i = 0; i < testString.length(); i++) {
char someChar = testString.charAt(i);
if (someChar == ' ') {
continue;
}
char ch = testString.charAt(i);
//Change to Optimize Code
Character keyCharacter = Character.toLowerCase(ch);
if (map.get(keyCharacter) == null) {
map.put(keyCharacter, new ArrayList<>());
}
List<Character> characters = map.get(keyCharacter);
characters.add(ch);
}
TreeMap<Integer, List<Character>> counterAppear = new TreeMap<>();
for (Map.Entry<Character, List<Character>> entry : map.entrySet()) {
Character character = entry.getKey();
int repeatCharTime = entry.getValue().size();
if (counterAppear.get(repeatCharTime) == null) {
counterAppear.put(repeatCharTime, new ArrayList<>());
}
List<Character> characters = counterAppear.get(repeatCharTime);
characters.add(character);
}
for (Integer repeatCharTime : counterAppear.descendingKeySet()) {
List<Character> keyCharacters = counterAppear.get(repeatCharTime);
Collections.sort(keyCharacters);
for (Character character : keyCharacters) {
for (int i = 0; i < repeatCharTime; i++) {
System.err.print(character);
}
}
}
}
Here's my solution:
import java.util.*;
public class Test
{
static void process(String s)
{
HashMap<Character,Integer> map = new HashMap<Character,Integer>();
for(Character c : s.toLowerCase().toCharArray())
{
Integer nb = map.get(c);
map.put(c, nb==null ? 1 : nb+1);
}
ArrayList<Map.Entry<Character,Integer>> list = new ArrayList<>(map.entrySet());
Collections.sort(list, (a,b) ->
{
int res = b.getValue().compareTo(a.getValue());
if(res!=0)
return res;
return a.getKey().compareTo(b.getKey());
});
for(Map.Entry<Character,Integer> e : list)
{
for(int i=0;i<e.getValue();i++)
System.out.print(e.getKey());
}
}
public static void main(String[] args)
{
process("Instructions");
}
}

Why is it returning the wrong amount of repetitions in the string?

I want to return the characters that are being repeated as well as the number of times it occurs but my output isn't consistent with what I'm expecting as the output.
It's outputting e 6 times when it should be 4 times as well as outputting j 1 time when it should be 2 times. I'm aware I'm returning it the wrong way as well.
What am I doing wrong and how can I fix it?
public static String solution(String s) {
int i, j, count = 0;
for(i = 0; i < s.length(); i++) {
for(j = i + 1; j < s.length(); j++) {
if(s.charAt(i) == s.charAt(j)) {
System.out.print(s.charAt(i) + " ");
count++;
}
}
}
System.out.println();
System.out.println("no duplicates");
System.out.println("There are " + count + " repetitions");
return s;
}
public static void main(String args[]) {
String s = "eeejiofewnj";
solution(s);
}
output:
e e e e e e j
no duplicates
There are 7 repititions
So what you are doing wrong is counting for each letter in the string, how many other letters after this one match it.
So for the first e your loop finds 3 matches, for the second e your loop finds 2 matches etc. and adds these all up.
What you want to do is count how many instances of a char there are in a String and then only display the ones that are higher than 1. The way I'd do it is with a map... like this:
public static String solution(String s) {
Map<Character, Integer> counts = new HashMap<Character, Integer>();
// Go through each char and make a map of char to their counts.
for (char c : s.toCharArray()) {
// See if the char is already in the map
Integer count = counts.get(c);
// if it wasn't then start counting from 1
if (count == null) {
count = 0;
}
count++;
// update the count
counts.put(c, count);
}
// now go through the map and print out any chars if their counts are higher than 1 (meaning there's a duplicate)
for (Entry<Character, Integer> entry : counts.entrySet()) {
if (entry.getValue() > 1) {
System.out.println(MessageFormat.format("there are {0} {1}s",
entry.getValue(), entry.getKey()));
}
}
return s;
}
public static void main(String args[]) {
String s = "eeejiofewnj";
solution(s);
}
Another alternative with Regular Expressions (discussed in more detail here).
public static void solutioniseThis(final String str)
{
Matcher repeatedMatcher = Pattern.compile("(\\w)\\1+").matcher(str);
while (repeatedMatcher.find())
{
int count = 0;
Matcher countMatcher = Pattern.compile(Matcher.quoteReplacement(repeatedMatcher.group(1))).matcher(str);
while (countMatcher.find())
{
count++;
}
System.out.println(MessageFormat.format("Repeated Character \"{0}\" - found {2} repetitions, {1} sequentially", repeatedMatcher.group(1),
repeatedMatcher.group(0).length(), count));
}
}
public static void main(String args[])
{
solutioniseThis("eeejiofewnj");
}
Produces an output of:
Repeated Character "e" - found 4 repetitions, 3 sequentially
You are counting each matching combination. For e (pseudocode):
CharAt(0) == CharAt(1)
CharAt(0) == CharAt(2)
CharAt(0) == CharAt(7)
CharAt(1) == CharAt(2)
CharAt(1) == CharAt(7)
CharAt(2) == CharAt(7)
For j there is only one:
CharAt(3) == CharAt(10)
hello this simple code also work:
public static void solution(String s) {
int[] repetitons = new int[128];
for (int i=0; i<s.length(); i++){
repetitons[(int)s.charAt(i)]++;
}
int count = 0;
for (int i=0; i<128; i++){
if (repetitons[i]>1){
count+=repetitons[i];
for (int j=0; j<repetitons[i]; j++){
System.out.print((char)i+" ");
}
}
}
System.out.println();
if (count == 0){
System.out.println("no duplicates");
} else {
System.out.println("There are " + count + " repetitions");
}
}
public static void main(String args[]) {
solution("eeejiofewnj");
}
Another solution using recursion.
public Map<Character, Integer> countRecursive(final String s)
{
final Map<Character, Integer> counts = new HashMap<Character, Integer>();
if(!s.isEmpty())
{
counts.putAll(countRecursive(s.substring(1)));
final char c = s.charAt(0);
if(counts.containsKey(c))
{
counts.put(c, counts.get(c) + 1);
}
else
{
counts.put(c, 1);
}
}
return counts;
}
public static void main(String args[])
{
final String s = "eeejiofewnj";
final Map<Character, Integer> counts = new CountCharacters().countRecursive(s);
for(Map.Entry<Character, Integer> count : counts.entrySet())
{
if (count.getValue() > 1)
{
System.out.println(MessageFormat.format("There are {0} {1}s",
count.getValue(), count.getKey()));
}
}
}
Another alternative with Java 8 and Apache Utils.
final String s = "eeejiofewnj";
new HashSet<>(s.chars().mapToObj(e->(char)e).collect(Collectors.toList())).stream().map(c -> Pair.of(c, StringUtils.countOccurrencesOf(s, "" + "" + c))).filter(count -> count.getRight() > 0).forEach(count -> System.out.println("There are " + count.getRight() + " repetitions of " + count.getLeft()));

How to find the most frequently occurring character in a string with Java?

Given a paragraph as input, find the most frequently occurring character. Note that the case of the character does not matter. If more than one character has the same maximum occurring frequency, return all of them
I was trying this question but I ended up with nothing. Following is the code that I tried but it has many errors I am unable to correct:
public class MaximumOccuringChar {
static String testcase1 = "Hello! Are you all fine? What are u doing today? Hey Guyz,Listen! I have a plan for today.";
public static void main(String[] args)
{
MaximumOccuringChar test = new MaximumOccuringChar();
char[] result = test.maximumOccuringChar(testcase1);
System.out.println(result);
}
public char[] maximumOccuringChar(String str)
{
int temp = 0;
int count = 0;
int current = 0;
char[] maxchar = new char[str.length()];
for (int i = 0; i < str.length(); i++)
{
char ch = str.charAt(i);
for (int j = i + 1; j < str.length(); j++)
{
char ch1 = str.charAt(j);
if (ch != ch1)
{
count++;
}
}
if (count > temp)
{
temp = count;
maxchar[current] = ch;
current++;
}
}
return maxchar;
}
}
You already got your answer here: https://stackoverflow.com/a/21749133/1661864
It's a most easy way I can imagine.
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class MaximumOccurringChar {
static final String TEST_CASE_1 = "Hello! Are you all fine? What are u doing today? Hey Guyz,Listen! I have a plan for today. Help!";
public static void main(String[] args) {
MaximumOccurringChar test = new MaximumOccurringChar();
List<Character> result = test.maximumOccurringChars(TEST_CASE_1, true);
System.out.println(result);
}
public List<Character> maximumOccurringChars(String str) {
return maximumOccurringChars(str, false);
}
// set skipSpaces true if you want to skip spaces
public List<Character> maximumOccurringChars(String str, Boolean skipSpaces) {
Map<Character, Integer> map = new HashMap<>();
List<Character> occurrences = new ArrayList<>();
int maxOccurring = 0;
// creates map of all characters
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (skipSpaces && ch == ' ') // skips spaces if needed
continue;
if (map.containsKey(ch)) {
map.put(ch, map.get(ch) + 1);
} else {
map.put(ch, 1);
}
if (map.get(ch) > maxOccurring) {
maxOccurring = map.get(ch); // saves max occurring
}
}
// finds all characters with maxOccurring and adds it to occurrences List
for (Map.Entry<Character, Integer> entry : map.entrySet()) {
if (entry.getValue() == maxOccurring) {
occurrences.add(entry.getKey());
}
}
return occurrences;
}
}
Why don't you simply use N letter buckets (N=number of letters in alphabet) ? Just go along the string and increment the corresponding letter bucket. Time complexity O(n), space complexity O(N)
This method allows you to find the most frequently occurring character in a string:
public char maximumOccuringChar(String str) {
return str.chars()
.mapToObj(x -> (char) x) // box to Character
.collect(groupingBy(x -> x, counting())) // collect to Map<Character, Long>
.entrySet().stream()
.max(comparingByValue()) // find entry with largest count
.get() // or throw if source string is empty
.getKey();
}
import java.util.Scanner;
public class MaximumOccurringChar{
static String testcase1 = "Hello! Are you all fine? What are u doing today? Hey Guyz,Listen! I have a plan for today.";
public static void main(String[] args) {
MaximumOccurringChar test = new MaximumOccurringChar();
String result = test.maximumOccuringChar(testcase1);
System.out.println(result);
}
public String maximumOccuringChar(String str) {
int temp = 0;
int count = 0;
int current = 0;
int ind = 0;
char[] arrayChar = {'a','b' , 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
int[] numChar = new int[26];
char ch;
String s="";
str = str.toLowerCase();
for (int i = 0; i < 26; i++) {
count = 0;
for (int j = 0; j < str.length(); j++) {
ch = str.charAt(j);
if (arrayChar[i] == ch) {
count++;
}
}
numChar[i] = count++;
}
temp = numChar[0];
for (int i = 1; i < numChar.length; i++) {
if (temp < numChar[i]) {
temp = numChar[i];
ind = i;
break;
}
}
System.out.println(numChar.toString());
for(int c=0;c<26;c++)
{
if(numChar[c]==temp)
s+=arrayChar[c]+" ";
}
return s;
}
}
Algorithm:-
Copying the String character by character to LinkedHashMap.
If its a new character then insert new character , 1.
If character is already present in the LinkedHashMap then update the value by incrementing by 1.
Iterating over the entry one by one and storing it in a Entry object.
If value of key stored in entry object is greater than or equal to current entry then do nothing
Else, store new entry in the Entry object
After looping through, simply print the key and value from Entry object.
public class Characterop {
public void maxOccur(String ip)
{
LinkedHashMap<Character, Integer> hash = new LinkedHashMap();
for(int i = 0; i<ip.length();i++)
{
char ch = ip.charAt(i);
if(hash.containsKey(ch))
{
hash.put(ch, (hash.get(ch)+1));
}
else
{
hash.put(ch, 1);
}
}
//Set set = hash.entrySet();
Entry<Character, Integer> maxEntry = null;
for(Entry<Character,Integer> entry : hash.entrySet())
{
if(maxEntry == null)
{
maxEntry = entry;
}
else if(maxEntry.getValue() < entry.getValue())
{
maxEntry = entry;
}
}
System.out.println(maxEntry.getKey());
}
public static void main(String[] args) {
Characterop op = new Characterop();
op.maxOccur("AABBBCCCCDDDDDDDDDD");
}
}
The Big O below solution is just o(n). Please share your opinion on it.
public class MaxOccuringCahrsInStr {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String str = "This is Sarthak Gupta";
printMaxOccuringChars(str);
}
static void printMaxOccuringChars(String str) {
char[] arr = str.toCharArray();
/* Assuming all characters are ascii */
int[] arr1 = new int[256];
int maxoccuring = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] != ' ') { // ignoring space
int val = (int) arr[i];
arr1[val]++;
if (arr1[val] > maxoccuring) {
maxoccuring = arr1[val];
}
}
}
for (int k = 0; k < arr1.length; k++) {
if (maxoccuring == arr1[k]) {
char c = (char) k;
System.out.print(c + " ");
}
}
}
}
function countString(ss)
{
var maxChar='';
var maxCount=0;
for(var i=0;i<ss.length;i++)
{
var charCount=0;
var localChar=''
for(var j=i+1;j<ss.length;j++)
{
if(ss[i]!=' ' && ss[i] !=maxChar)
if(ss[i]==ss[j])
{
localChar=ss[i];
++charCount;
}
}
if(charCount>maxCount)
{
maxCount=charCount;
maxChar=localChar;
}
}
alert(maxCount+""+maxChar)
}
Another way to solve it. A simpler one.
public static void main(String[] args) {
String str= "aaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbcddddeeeeee";
String str1 = "dbc";
if(highestOccuredChar(str) != ' ')
System.out.println("Most Frequently occured Character ==> " +Character.toString(highestOccuredChar(str)));
else
System.out.println("The String doesn't have any character whose occurance is more than 1");
}
private static char highestOccuredChar(String str) {
int [] count = new int [256];
for ( int i=0 ;i<str.length() ; i++){
count[str.charAt(i)]++;
}
int max = -1 ;
char result = ' ' ;
for(int j =0 ;j<str.length() ; j++){
if(max < count[str.charAt(j)] && count[str.charAt(j)] > 1) {
max = count[str.charAt(j)];
result = str.charAt(j);
}
}
return result;
}
public void countOccurrence(String str){
int length = str.length();
char[] arr = str.toCharArray();
HashMap<Character, Integer> map = new HashMap<>();
int max = 0;
for (char ch : arr) {
if(ch == ' '){
continue;
}
if (map.containsKey(ch)) {
map.put(ch, map.get(ch) + 1);
} else {
map.put(ch, 1);
}
}
Set<Character> set = map.keySet();
for (char c : set) {
if (max == 0 || map.get(c) > max) {
max = map.get(c);
}
}
for (Character o : map.keySet()) {
if (map.get(o).equals(max)) {
System.out.println(o);
}
}
System.out.println("");
}
public static void main(String[] args) {
HighestOccurence ho = new HighestOccurence();
ho.countOccurrence("aabbbcde");
}
public void stringMostFrequentCharacter() {
String str = "My string lekdcd dljklskjffslk akdjfjdkjs skdjlaldkjfl;ak adkj;kfjflakj alkj;ljsfo^wiorufoi$*#&$ *******";
char[] chars = str.toCharArray(); //optionally - str.toLowerCase().toCharArray();
int unicodeMaxValue = 65535; // 4 bytes
int[] charCodes = new int[unicodeMaxValue];
for (char c: chars) {
charCodes[(int)c]++;
}
int maxValue = 0;
int maxIndex = 0;
for (int i = 0; i < unicodeMaxValue; i++) {
if (charCodes[i] > maxValue) {
maxValue = charCodes[i];
maxIndex = i;
}
}
char maxChar = (char)maxIndex;
System.out.println("The most frequent character is >" + maxChar + "< - # of times: " + maxValue);
}
For Simple String Manipulation, this program can be done as:
package abc;
import java.io.*;
public class highocc
{
public static void main(String args[])throws IOException
{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter any word : ");
String str=in.readLine();
str=str.toLowerCase();
int g=0,count,max=0;;
int ar[]=new int[26];
char ch[]={'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
for(int i=0;i<ch.length;i++)
{
count=0;
for(int j=0;j<str.length();j++)
{
char ch1=str.charAt(j);
if(ch[i]==ch1)
count++;
}
ar[i]=(int) count;
}
max=ar[0];
for(int j=1;j<26;j++)
{
if(max<ar[j])
{
max=ar[j];
g=j;
}
}
System.out.println("Maximum Occurence is "+max+" of character "+ch[g]);
}
}
Sample Input1: Pratik is a good Programmer
Sample Output1: Maximum Occurence is 3 of character a
Sample Input2: hello WORLD
Sample Output2: Maximum Occurence is 3 of character l
maxOccu m = new maxOccu();
String str = "moinnnnaaooooo";
char[] chars = str.toCharArray();
Arrays.sort(chars);
str = new String(chars);
System.out.println(str);
m.maxOccurence(str);
void maxOccurence(String str) {
char max_char = str.charAt(0),
cur_char,
prev = str.charAt(0);
int cur_count = 0,
max_count = 0,
n;
n = str.length();
for (int i = 0; i < n; i++) {
cur_char = str.charAt(i);
if (cur_char != prev) cur_count = 0;
if (str.charAt(i) == cur_char) {
cur_count++;
}
if (cur_count > max_count) {
max_count = cur_count;
max_char = cur_char;
}
prev = cur_char;
}
System.out.println(max_count + "" + max_char);
}
public class HigestOccurredCharTest {
public static void main(String[] args) {
System.out.println("Enter the char string to check higest occurrence");
Scanner scan = new Scanner(System.in);
String str = scan.next();
if(str != null && !str.isEmpty()){
Map<Character, Integer> map = countOccurrence(str);
getHigestOccurrenceChar(map);
}else{
System.out.println("enter valid string");
}
}
public static Map<Character, Integer> countOccurrence(String str){
char strArr[] = str.toCharArray();
Map<Character, Integer> map = new HashMap<Character , Integer>();
for (Character ch : strArr) {
if(map.containsKey(ch)){
map.put(ch, map.get(ch)+1);
}else{
map.put(ch, 1);
}
}
return map;
}
public static void getHigestOccurrenceChar(Map<Character, Integer> map){
Character ch = null;
Integer no = 0;
Set<Entry<Character, Integer>> entrySet = map.entrySet();
for (Entry<Character, Integer> entry : entrySet) {
if(no != 0 && ch != null){
if(entry.getValue() > no){
no = entry.getValue();
ch = entry.getKey();
}
}else{
no = entry.getValue();
ch = entry.getKey();
}
}
System.out.println(ch+ " Higest occurrence char is "+ no);
}
}
Try Like that:-
string inputString = "COMMECEMENT";
List<Tuple<char, int>> allCharListWithLength = new List<Tuple<char, int>>();
List<char> distinchtCharList = inputString.Select(r => r).Distinct().ToList();
for (int i = 0; i < distinchtCharList.Count; i++)
{
allCharListWithLength.Add(new Tuple<char, int>(distinchtCharList[i], inputString.Where(r => r ==
distinchtCharList[i]).Count()));
}
Tuple<char, int> charWithMaxLength = allCharListWithLength.Where(r => r.Item2 == allCharListWithLength.Max(x => x.Item2)).FirstOrDefault();
Question: Frequently occurring Character in a String
Method 1: Using HashMap
public class t1{
public static void main(String a[]){
Map<Character, Integer> map = new HashMap<>();
String a1 = "GiinnniiiiGiiinnnnnaaaProtijayi";
for(char ch : a1.toCharArray()) {map.put(ch, map.getOrDefault(ch,0)+1);}//for
System.out.println(map);
char maxchar = 0 ;
int maxvalue = Collections.max(map.values());
System.out.println("maxvalue => " + maxvalue);
for( Entry<Character,Integer> entry : map.entrySet()) {
if(entry.getValue() == maxvalue) {
System.out.println("most frequent Character => " + entry.getKey());
}
}//for
}
}
Method 2 : Using count of alphabets in Python
str = "GiinnniiiiGiiinnnnnaaaProtijayi";
count = [0]*256
maxcount= -1
longestcharacter =""
# Traversing through the string and maintaining the count of
# each character
for ch in str:count[ord(ch)] += 1;
for ch in str:
if( maxcount < count[ord(ch)] ):
maxcount = count[ord(ch)]
longestcharacter = ch
print(longestcharacter)
print(maxcount)
IN Java :
public class t1{
public static void main(String[] args) {
String a = "GiinnniiiiGiiinnnnnaaaProtijayi";
int[] count = new int[256];
for (int i = 0; i < a.length(); i++) {
char ch = a.charAt(i);
count[ch] +=1;
}//for
int maxcount = -1 ;
char longest = 0 ;
for( char ch : a.toCharArray()) {
if(count[ch] > maxcount) {
maxcount = count[ch];
longest = ch ;
}//if
}//for
System.out.println(longest);
System.out.println(maxcount);
}//main
}
Method 3: Using collections.Counter().most_common()
import collections
a = "GiinnniiiiGiiinnnnnaaaProtijayi";
fullDictionary = collections.Counter(a).most_common()
FirstElementWithCount = fullDictionary[0]
print(FirstElementWithCount)
FirstElementWithoutCount = FirstElementWithCount[0]
print(FirstElementWithoutCount)
Method 4: Using sorted and key = lambda ch : ch[1]
a = "GiinnniiiiGiiinnnnnaaaProtijayi";
d = {}
for ch in a: d[ch] = d.get(ch, 0) + 1
fullDictionary = sorted(d.items(), key=lambda ch :ch[1], reverse=True)
print(fullDictionary)
FirstElement = fullDictionary[0][0]
print(FirstElement)
package com.practice.ArunS;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
public class HighestFrequencyElement {
/*
* CONTENTSERV=N(2),T(2),E(2) SearchSort=S(2),r(2)
* HighestFrequencyElement=E(5)
*/
public static void main(String[] args) {
String str = "CONTENTSERV";
findHighestFrequencyElement(str);
}
private static void findHighestFrequencyElement(String str) {
System.out.println("Original String:" + str);
Map<String, Integer> myMap = new TreeMap<String, Integer>();
char[] ch = str.toCharArray();
for (int i = 0; i < str.length(); i++) {
if (myMap.containsKey(Character.toString(ch[i]))) {
Integer value = myMap.get(Character.toString(ch[i]));
myMap.replace(Character.toString(ch[i]), ++value);
} else {
myMap.put(Character.toString(ch[i]), 1);
}
} // end of foor loop
Comparator<Entry<String, Integer>> valueComparator = new Comparator<Entry<String, Integer>>() {
#Override
public int compare(Entry<String, Integer> e1, Entry<String, Integer> e2) {
Integer v1 = e1.getValue();
Integer v2 = e2.getValue();
return v2-v1;
}
};
// Sort method needs a List, so let's first convert Set to List in Java
List<Entry<String, Integer>> listOfEntries = new ArrayList<Entry<String, Integer>>(myMap.entrySet());
// sorting HashMap by values using comparator
Collections.sort(listOfEntries, valueComparator);
for(int i=0;i<listOfEntries.size();i++){
if(listOfEntries.get(0).getValue()==listOfEntries.get(i).getValue()){
System.out.println(listOfEntries.get(i));
}
}
}//end of method
}
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.function.Predicate;
import java.util.stream.Collectors;
public class Answers {
public static void main(String[] args) {
String input1 = "Hello! Are you all fine? What are u doing today? Hey Guyz,Listen! I have a plan for today.";
String[] arin = input1.split("");
Predicate<String> checkIfValidChar = str -> ((str.charAt(0) >= '0' && str.charAt(0) <= '9')
|| (str.charAt(0) >= 'a' && str.charAt(0) <= 'z')
|| (str.charAt(0) >= 'A' && str.charAt(0) <= 'Z'));
String maxChar = Arrays.stream(arin).max(Comparator.comparing(i -> Arrays.stream(arin).filter(j -> {
return i.equalsIgnoreCase(j) && checkIfValidChar.test(j);
}).count())).get();
int count = Collections.frequency(Arrays.asList(arin), maxChar);
System.out.println(Arrays.stream(arin).filter(i -> {
return Collections.frequency(Arrays.asList(arin), i) == count && checkIfValidChar.test(i);
}).collect(Collectors.toSet()));
}
}
I see many answers that are unnecessarily convoluted, import tons of stuff or use a cannon to shoot a mosquito ( the accepted answer uses an HashTable ).
Here a simple solution:
public List<Character> mostFrequentLetter(String message) {
var m = message
.replaceAll("[^a-z]", "")
.toLowerCase();
int[] count = new int[26];
for(var c : m.toCharArray()){
int i = ((int)c)-97;
count[i]++;
}
var max_i = 0; // index of the most frequent letter
var max_c = count[max_i]; // count of the most frequent letter
var max = new ArrayList<Character>(3); // list containing letters with the same frequency
for(int i = 1; i < 26; ++i){
if (count[i] >= max_c){
max_i = i;
char c = (char)(max_i + 97);
if(count[i]!=max_c){
max.clear();
max_c = count[i];
}
max.add(c);
}
}
return max;
}
Here str will be the given string. This is Javascript code
function maxCharacter(str){
let str1 = str; let reptCharsCount=0; let ele='';let maxCount=0;
let charArr = str1.split('');
for(let i=0; i< str1.length; i++){
reptCharsCount=0;
for(let j=0; j< str1.length; j++){
if(str1[i] === str1[j]) {
reptCharsCount++;
}
}
if(reptCharsCount > maxCount) {
ele = str1[i];
maxCount = reptCharsCount;
}
}
return ele;
}
Although all the answers are correct posting my way of doing it
/Question: For the given string such as "aabbbbbcc" print the longest occurring character,
index and number of times it occurs.
Ex:
"longest occurring character is b and length is 5 at index 2"./
class Codechef {
public static void main (String[] args) {
String problem = "aabbbbbcc";
Map<Character,Temp> map = new HashMap<>();
for(int i = 0; i < problem.length(); i++){
if (map.containsKey(problem.charAt(i))) {
map.get(problem.charAt(i)).incrementCount();
} else {
map.put(problem.charAt(i), new Temp(i, 1, problem.charAt(i)));
}
}
List<Map.Entry<Character, Temp>> listOfValue = new LinkedList<Map.Entry<Character, Temp>>(map.entrySet());
Comparator<Map.Entry<Character, Temp>> comp = (val1, val2) -> (val1.getValue().getCount() < val2.getValue().getCount() ? 1: -1);
Collections.sort(listOfValue, comp);
Temp tmp = listOfValue.get(0).getValue();
System.out.println("longest occurring character is "+ tmp.getStr()+ " and length is " + tmp.getCount()+ " at index "+ tmp.getIndex());
}}
And then created one Model class to keep these values
class Temp {
Integer index;
Integer count;
Character str;
public Temp(Integer index, Integer count, Character str ){
this.index = index;
this.count = count;
this.str = str;
}
public void incrementCount(){
this.count++;
}
public Integer getCount(){
return count;
}
public Character getStr(){
return str;
}
public Integer getIndex(){
return index;
}}
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
public class Maxchar {
public static void main(String[] args) {
String str = "vaquar khan.";
// System.out.println();
System.out.println(maxChar(str));
String testcase1 = "Hello! Are you all fine? What are u doing today? Hey Guyz,Listen! I have a plan for today.";
System.out.println(maxChar(testcase1));
}
private static char maxChar(String str) {
if (null == str)
return ' ';
char[] charArray = str.replaceAll("\s+", "").toCharArray();
//
Map<Character, Integer> maxcharmap = new HashMap<Character, Integer>();
//
for (char c : charArray) {
if (maxcharmap.containsKey(c)) {
maxcharmap.put(c, maxcharmap.get(c) + 1);
} else {
maxcharmap.put(c, 1);
}
// Inside map we have word count
// System.out.println(maxcharmap.toString());
}
//
//
Set<Entry<Character, Integer>> entrySet = maxcharmap.entrySet();
int count = 0;
char maxChar = 0;
//
for (Entry<Character, Integer> entry : entrySet) {
if (entry.getValue() > count) {
count = entry.getValue();
maxChar = entry.getKey();
}
}
System.out.println("Maximum Occurring char and its count :");
System.out.println(maxChar + " : " + count);
return maxChar;
}
}
If you're open to 3rd party libraries you could use the Bag type from Eclipse Collections and select the top occurrences.
public char[] maxOccurringChar(String s) {
MutableCharBag bag = CharBags.mutable.of(s.toCharArray());
MutableList<CharIntPair> maxOccurringCharsWithCounts = bag.topOccurrences(1);
MutableCharList maxOccurringChars = maxOccurringCharsWithCounts.collectChar(CharIntPair::getOne);
return maxOccurringChars.toArray();
}
Note in this example we used the primitive collections to avoid boxing of the char and int types.
import java.util.*;
import java.util.stream.*;
class MaxOccur{
public static void main(String[] args){
String str = "sfowfjalkfaeffawkefjweajjwjegjoweeowe";
maxOcc(str);
}
public static void maxOcc(String s){
ArrayList<Character> arr = (ArrayList<Character>) s.chars().mapToObj(e ->(char)e).collect(Collectors.toList());
HashSet<Character> hs = new HashSet<>(arr);
int max = 0;
int f = 0;
String answer = "";
for(Character ch : hs){
f = Collections.frequency(arr,ch);
if(f>max){
max = f;
answer = ch;
}
System.out.println(ch + " occurs " + max + " times, the maximum");
}
}
In above, I'm using streams. Following are the steps:
Converting string's characters to arraylist using streams.
Making a hashset (discards all duplicate occurences of characters) using the arrayList created in step 1.
Use Collections.frequency to count occurence of each character in arrayList.
It's not the easiest solution, neither is it really adorable! But, it makes use of streams, something which i recently started learning and wanted to apply. I'm no adept in using streams, but they are beautiful. I've learnt most of them here on stackoverflow, and i'm so grateful. :)
Map the chars to their occurrence then query entries for the max value and get its key, note this will return the first char that has the highest occurrence
"abc".chars().mapToObj(c -> (char) c)
.collect(Collectors.groupingBy(Function.identity(),Collectors.counting()))
.entrySet()
.stream()
.max(Comparator.comparingLong(Map.Entry::getValue))
.get()
.getKey();
Here I am posting the answer by using HashMap
public class maximumOccurrence {
public static Map<Character,Integer> maximumOccurence(String s) {
char maxchar='';
int maxint=0;
Map<Character,Integer> map = new HashMap<Character, Integer>();
char strAtt[]= s.toCharArray();
for(Character ch : strAtt) {
if(map.containsKey(ch)) {
map.put(ch, map.get(ch)+1);
}else {
map.put(ch,1);
}
}
for(Map.Entry<Character,Integer> entry : map.entrySet()) {
System.out.println(entry.getKey() + "/" + entry.getValue());
if(maxint<entry.getValue()) {
maxint=entry.getValue();
maxchar=entry.getKey();
}
}
System.out.println("Character repeated ="+maxchar+" it's value is:"+maxint);
return map;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
String s= "uuuiiiiiiiiiiioooooopp";
System.out.println(maximumOccurence(s));
}
}

Find duplicate characters in a String and count the number of occurrences using Java

How can I find the number of occurrences of a character in a string?
For example: The quick brown fox jumped over the lazy dog.
Some example outputs are below,
'a' = 1
'o' = 4
'space' = 8
'.' = 1
You could use the following, provided String s is the string you want to process.
Map<Character,Integer> map = new HashMap<Character,Integer>();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (map.containsKey(c)) {
int cnt = map.get(c);
map.put(c, ++cnt);
} else {
map.put(c, 1);
}
}
Note, it will count all of the chars, not only letters.
Java 8 way:
"The quick brown fox jumped over the lazy dog."
.chars()
.mapToObj(i -> (char) i)
.collect(Collectors.groupingBy(Object::toString, Collectors.counting()));
void Findrepeter(){
String s="mmababctamantlslmag";
int distinct = 0 ;
for (int i = 0; i < s.length(); i++) {
for (int j = 0; j < s.length(); j++) {
if(s.charAt(i)==s.charAt(j))
{
distinct++;
}
}
System.out.println(s.charAt(i)+"--"+distinct);
String d=String.valueOf(s.charAt(i)).trim();
s=s.replaceAll(d,"");
distinct = 0;
}
}
import java.io.*;
public class CountChar
{
public static void main(String[] args) throws IOException
{
String ch;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter the Statement:");
ch=br.readLine();
int count=0,len=0;
do
{
try
{
char name[]=ch.toCharArray();
len=name.length;
count=0;
for(int j=0;j<len;j++)
{
if((name[0]==name[j])&&((name[0]>=65&&name[0]<=91)||(name[0]>=97&&name[0]<=123)))
count++;
}
if(count!=0)
System.out.println(name[0]+" "+count+" Times");
ch=ch.replace(""+name[0],"");
}
catch(Exception ex){}
}
while(len!=1);
}
}
Output
Enter the Statement:asdf23123sfsdf
a 1 Times
s 3 Times
d 2 Times
f 3 Times
A better way would be to create a Map to store your count. That would be a Map<Character, Integer>
You need iterate over each character of your string, and check whether its an alphabet. You can use Character#isAlphabetic method for that. If it is an alphabet, increase its count in the Map. If the character is not already in the Map then add it with a count of 1.
NOTE: - Character.isAlphabetic method is new in Java 7. If you are using an older version, you should use Character#isLetter
String str = "asdfasdfafk asd234asda";
Map<Character, Integer> charMap = new HashMap<Character, Integer>();
char[] arr = str.toCharArray();
for (char value: arr) {
if (Character.isAlphabetic(value)) {
if (charMap.containsKey(value)) {
charMap.put(value, charMap.get(value) + 1);
} else {
charMap.put(value, 1);
}
}
}
System.out.println(charMap);
OUTPUT: -
{f=3, d=4, s=4, a=6, k=1}
If your string only contains alphabets then you can use some thing like this.
public class StringExample {
public static void main(String[] args) {
String str = "abcdabghplhhnfl".toLowerCase();
// create a integer array for 26 alphabets.
// where index 0,1,2.. will be the container for frequency of a,b,c...
Integer[] ar = new Integer[26];
// fill the integer array with character frequency.
for(int i=0;i<str.length();i++) {
int j = str.charAt(i) -'a';
if(ar[j]==null) {
ar[j]= 1;
}else {
ar[j]+= 1;
}
}
// print only those alphabets having frequency greater then 1.
for(int i=0;i<ar.length;i++) {
if(ar[i]!=null && ar[i]>1) {
char c = (char) (97+i);
System.out.println("'"+c+"' comes "+ar[i]+" times.");
}
}
}
}
Output:
'a' comes 2 times.
'b' comes 2 times.
'h' comes 3 times.
'l' comes 2 times.
Finding the duplicates in a String:
Example 1 : Using HashMap
public class a36 {
public static void main(String[] args) {
String a = "Gini Rani";
fix(a);
}//main
public static void fix(String a ){
Map<Character ,Integer> map = new HashMap<>();
for (int i = 0; i <a.length() ; i++ ) {
char ch = a.charAt(i);
map.put(ch , map.getOrDefault(ch,0) +1 );
}//for
List<Character> list = new ArrayList<>();
Set<Map.Entry<Character ,Integer> > entrySet = map.entrySet();
for ( Map.Entry<Character ,Integer> entry : entrySet) {
list.add( entry.getKey() );
System.out.printf( " %s : %d %n" , entry.getKey(), entry.getValue() );
}//for
System.out.println("Duplicate elements => " + list);
}//fix
}
Example 2 : using Arrays.stream() in Java 8
public class a37 {
public static void main(String[] args) {
String aa = "Protijayi Gini";
String[] stringarray = aa.split("");
Map<String , Long> map = Arrays.stream(stringarray)
.collect(Collectors.groupingBy(c -> c , Collectors.counting()));
map.forEach( (k, v) -> System.out.println(k + " : "+ v) );
}
}
This is the implementation without using any Collection and with complexity order of n. Although the accepted solution is good enough and does not use Collection as well but it seems, it is not taking care of special characters.
import java.util.Arrays;
public class DuplicateCharactersInString {
public static void main(String[] args) {
String string = "check duplicate charcters in string";
string = string.toLowerCase();
char[] charAr = string.toCharArray();
Arrays.sort(charAr);
for (int i = 1; i < charAr.length;) {
int count = recursiveMethod(charAr, i, 1);
if (count > 1) {
System.out.println("'" + charAr[i] + "' comes " + count + " times");
i = i + count;
} else
i++;
}
}
public static int recursiveMethod(char[] charAr, int i, int count) {
if (ifEquals(charAr[i - 1], charAr[i])) {
count = count + recursiveMethod(charAr, ++i, count);
}
return count;
}
public static boolean ifEquals(char a, char b) {
return a == b;
}
}
Output :
' ' comes 4 times
'a' comes 2 times
'c' comes 5 times
'e' comes 3 times
'h' comes 2 times
'i' comes 3 times
'n' comes 2 times
'r' comes 3 times
's' comes 2 times
't' comes 3 times
public class dublicate
{
public static void main(String...a)
{
System.out.print("Enter the String");
Scanner sc=new Scanner(System.in);
String st=sc.nextLine();
int [] ar=new int[256];
for(int i=0;i<st.length();i++)
{
ar[st.charAt(i)]=ar[st.charAt(i)]+1;
}
for(int i=0;i<256;i++)
{
char ch=(char)i;
if(ar[i]>0)
{
if(ar[i]==1)
{
System.out.print(ch);
}
else
{
System.out.print(ch+""+ar[i]);
}
}
}
}
}
Use google guava Multiset<String>.
Multiset<String> wordsMultiset = HashMultiset.create();
wordsMultiset.addAll(words);
for(Multiset.Entry<E> entry:wordsMultiset.entrySet()){
System.out.println(entry.getElement()+" - "+entry.getCount());
}
public static void main(String args[]) {
char Char;
int count;
String a = "Hi my name is Rahul";
a = a.toLowerCase();
for (Char = 'a'; Char <= 'z'; Char++) {
count = 0;
for (int i = 0; i < a.length(); i++) {
if (a.charAt(i) == Char) {
count++;
}
}
System.out.println("Number of occurences of " + Char + " is " + count);
}
}
public static void main(String[] args) {
String name="AnuvratAnuvra";
char[] arr = name.toCharArray();
HashMap<Character, Integer> map = new HashMap<Character, Integer>();
for(char val:arr){
map.put(val,map.containsKey(val)?map.get(val)+1:1);
}
for (Entry<Character, Integer> entry : map.entrySet()) {
if(entry.getValue()>1){
Character key = entry.getKey();
Object value = entry.getValue();
System.out.println(key + ":"+value);
}
}
}
class A {
public static void getDuplicates(String S) {
int count = 0;
String t = "";
for (int i = 0; i < S.length() - 1; i++) {
for (int j = i + 1; j < S.length(); j++) {
if (S.charAt(i) == S.charAt(j) && !t.contains(S.charAt(j) + "")) {
t = t + S.charAt(i);
}
}
}
System.out.println(t);
}
}
class B
public class B {
public static void main(String[] args){
A.getDuplicates("mymgsgkkabcdyy");
}
}
You can also achieve it by iterating over your String and using a switch to check each individual character, adding a counter whenever it finds a match. Ah, maybe some code will make it clearer:
Main Application:
public static void main(String[] args) {
String test = "The quick brown fox jumped over the lazy dog.";
int countA = 0, countO = 0, countSpace = 0, countDot = 0;
for (int i = 0; i < test.length(); i++) {
switch (test.charAt(i)) {
case 'a':
case 'A': countA++; break;
case 'o':
case 'O': countO++; break;
case ' ': countSpace++; break;
case '.': countDot++; break;
}
}
System.out.printf("%s%d%n%s%d%n%s%d%n%s%d", "A: ", countA, "O: ", countO, "Space: ", countSpace, "Dot: ", countDot);
}
Output:
A: 1
O: 4
Space: 8
Dot: 1
import java.util.HashMap;
import java.util.Scanner;
public class HashMapDemo {
public static void main(String[] args) {
//Create HashMap object to Store Element as Key and Value
HashMap<Character,Integer> hm= new HashMap<Character,Integer>();
//Enter Your String From Console
System.out.println("Enter an String:");
//Create Scanner Class Object From Retrive the element from console to our java application
Scanner sc = new Scanner(System.in);
//Store Data in an string format
String s1=sc.nextLine();
//find the length of an string and check that hashmap object contain the character or not by using
//containskey() if that map object contain element only one than count that value as one or if it contain more than one than increment value
for(int i=0;i<s1.length();i++){
if(!hm.containsKey(s1.charAt(i))){
hm.put(s1.charAt(i),(Integer)1);
}//if
else{
hm.put(s1.charAt(i),hm.get(s1.charAt(i))+1);
}//else
}//for
System.out.println("The Charecters are:"+hm);
}//main
}//HashMapDemo
There are three ways to find duplicates
public class WAP_PrintDuplicates {
public static void main(String[] args) {
String input = "iabccdeffghhijkkkl";
findDuplicate1(input);
findDuplicate2(input);
findDuplicate3(input);
}
private static void findDuplicate3(String input) {
HashMap<Character, Integer> hm = new HashMap<Character, Integer>();
for (int i = 0; i < input.length() - 1; i++) {
int ch = input.charAt(i);
if (hm.containsKey(input.charAt(i))) {
int value = hm.get(input.charAt(i));
hm.put(input.charAt(i), value + 1);
} else {
hm.put(input.charAt(i), 1);
}
}
Set<Entry<Character, Integer>> entryObj = hm.entrySet();
for (Entry<Character, Integer> entry : entryObj) {
if (entry.getValue() > 1) {
System.out.println("Duplicate: " + entry.getKey());
}
}
}
private static void findDuplicate2(String input) {
int i = 0;
for (int j = i + 1; j < input.length(); j++, i++) {
if (input.charAt(i) == input.charAt(j)) {
System.out.println("Duplicate is: " + input.charAt(i));
}
}
}
private static void findDuplicate1(String input) {
// TODO Auto-generated method stub
for (int i = 0; i < input.length(); i++) {
for (int j = i + 1; j < input.length(); j++) {
if (input.charAt(i) == input.charAt(j)) {
System.out.println("Duplicate is: " + input.charAt(i));
}
}
}
}
}
Using Eclipse Collections CharAdapter and CharBag:
CharBag bag =
Strings.asChars("The quick brown fox jumped over the lazy dog.").toBag();
Assert.assertEquals(1, bag.occurrencesOf('a'));
Assert.assertEquals(4, bag.occurrencesOf('o'));
Assert.assertEquals(8, bag.occurrencesOf(' '));
Assert.assertEquals(1, bag.occurrencesOf('.'));
Note: I am a committer for Eclipse Collections
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
public class DuplicateCountChar{
public static void main(String[] args) {
Scanner inputString = new Scanner(System.in);
String token = inputString.nextLine();
char[] ch = token.toCharArray();
Map<Character, Integer> dupCountMap = new HashMap<Character,Integer>();
for (char c : ch) {
if(dupCountMap.containsKey(c)) {
dupCountMap.put(c, dupCountMap.get(c)+1);
}else {
dupCountMap.put(c, 1);
}
}
for (char c : ch) {
System.out.println("Key = "+c+ "Value : "+dupCountMap.get(c));
}
Set<Character> keys = dupCountMap.keySet();
for (Character character : keys) {
System.out.println("Key = "+character+ " Value : " + dupCountMap.get(character));
}
}**
In java... using for loop:
import java.util.Scanner;
/**
*
* #author MD SADDAM HUSSAIN */
public class Learn {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
String input = sc.next();
char process[] = input.toCharArray();
boolean status = false;
int index = 0;
for (int i = 0; i < process.length; i++) {
for (int j = 0; j < process.length; j++) {
if (i == j) {
continue;
} else {
if (process[i] == process[j]) {
status = true;
index = i;
break;
} else {
status = false;
}
}
}
if (status) {
System.out.print("" + process[index]);
}
}
}
}
public class StringCountwithOutHashMap {
public static void main(String[] args) {
System.out.println("Plz Enter Your String: ");
Scanner sc = new Scanner(System.in);
String s1 = sc.nextLine();
int count = 0;
for (int i = 0; i < s1.length(); i++) {
for (int j = 0; j < s1.length(); j++) {
if (s1.charAt(i) == s1.charAt(j)) {
count++;
}
}
System.out.println(s1.charAt(i) + " --> " + count);
String d = String.valueOf(s1.charAt(i)).trim();
s1 = s1.replaceAll(d, "");
count = 0;
}}}
public class CountH {
public static void main(String[] args) {
String input = "Hi how are you";
char charCount = 'h';
int count = 0;
input = input.toLowerCase();
for (int i = 0; i < input.length(); i++) {
if (input.charAt(i) == charCount) {
count++;
}
}
System.out.println(count);
}
}
public class DuplicateValue {
public static void main(String[] args) {
String s = "hezzz";
char []st=s.toCharArray();
int count=0;
Set<Character> ch=new HashSet<>();
for(Character cg:st){
if(ch.add(cg)==false){
int occurrences = Collections.frequency(ch, cg);
count+=occurrences;
if(count>1){
System.out.println(cg + ": This character exist more than one time");
}
else{
System.out.println(cg);
}
}
}
System.out.println(count);
}
}
Map<Character,Integer> listMap = new HashMap<Character,Integer>();
Scanner in= new Scanner(System.in);
System.out.println("enter the string");
String name=in.nextLine().toString();
Integer value=0;
for(int i=0;i<name.length();i++){
if(i==0){
listMap.put(name.charAt(0), 1);
}
else if(listMap.containsKey(name.charAt(i))){
value=listMap.get(name.charAt(i));
listMap.put(name.charAt(i), value+1);
}else listMap.put(name.charAt(i),1);
}
System.out.println(listMap);
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
String reverse1;
String reverse2;
int count = 0;
while(n > 0)
{
String A = sc.next();
String B = sc.next();
reverse1 = new StringBuffer(A).reverse().toString();
reverse2 = new StringBuffer(B).reverse().toString();
if(!A.equals(reverse1))
{
for(int i = 0; i < A.length(); i++)
{
for(int j = 0; j < A.length(); j++)
{
if(A.charAt(j) == A.charAt(i))
{
count++;
}
}
if(count % 2 != 0)
{
A.replace(A.charAt(i),"");
count = 0;
}
}
System.out.println(A);
}
n--;
}
}
}
public class list {
public static String name(Character k){
String s="the quick brown fox jumped over the lazy dog.";
int count=0;
String l1="";
String l="";
List<Character> list=new ArrayList<Character>();
for(int i1=0;i1<s.length();i1++){
list.add(s.charAt(i1));
}
list.sort(null);
for (Character character : list) {
l+=character;
}
for (int i1=0;i1<l.length();i1++) {
if((l.charAt(i1)==k)){
count+=1;
l1=l.charAt(i1)+" "+Integer.toString(count);
if(k==' '){
l1="Space"+" "+Integer.toString(count);
}
}else{
count=0;
}
}
return l1;
}
public static void main(String[] args){
String g = name('.');
System.out.println(g);
}
}
Simple and Easy way to find char occurrences >
void findOccurrences() {
String s = "The quick brown fox jumped over the lazy dog.";
Map<String, Integer> occurrences = new LinkedHashMap<String, Integer>();
for (String ch : s.split("")) {
Integer count = occurrences.get(ch);
occurrences.put(ch, count == null ? 1 : count + 1);
}
System.out.println(occurrences);
}
This will print output as:
{T=1, h=2, e=4, =8, q=1, u=2, i=1, c=1, k=1, b=1, r=2, o=4, w=1, n=1, f=1, x=1, j=1, m=1, p=1, d=2, v=1, t=1, l=1, a=1, z=1, y=1, g=1, .=1}
String str = "anand";
Map<Character, Integer> map
= new HashMap<Character, Integer>();
// Converting string into a char array
char[] charArray = str.toCharArray();
for (char c : charArray) {
if (map.containsKey(c)) {
// If character is present increment count by 1
map.put(c, map.get(c) + 1);
}
else {
// If character is not present
//putting this character into map with 1 as it's value.
map.put(c, 1);
}
}
for (Map.Entry<Character, Integer> entry :
map.entrySet()) {
System.out.println(entry.getKey()
+ " : "
+ entry.getValue());
}
Output:
a:2 n:2 d:1
Use the below code snippet
import java.util.HashMap;
import java.util.Map;
public class CountDuplicateChar {
public static void main(String... strings) {
withSortedString("aaaaabbcccccc");
withUnSortedString("aaaaab bcc *#ccccf");
withHashMap("bala");
}
private static void withHashMap(String inputString) {
Map<Character, Integer> map = new HashMap<>();
char[] charArray = inputString.toCharArray();
for (int i = 0 ; i < charArray.length ; i++ ){
if (map.containsKey(charArray[i])) {
map.put(charArray[i], map.get(charArray[i]) +1);
} else {
map.put(charArray[i], 1);
}
}
System.out.println(map);
}
private static void withUnSortedString(String unSortedString) {
int len = 0;
do {
char[] ch = unSortedString.toCharArray();
if (ch.length ==0)
break;
int count = 0 ;
for ( int i = 0 ; i < ch.length; i++) {
if (ch[0] == ch[i]) {
count++;
}
}
System.out.println(ch[0] + " - " + count + "times");
unSortedString = unSortedString.replace(""+ch[0],"");
}while (len!=1);
}
private static void withSortedString(String s) {
for(int i=0; i<s.length(); i++)
{
System.out.print(s.charAt(i)+""+(s.lastIndexOf(s.charAt(i))-s.indexOf(s.charAt(i))+1));
i = s.lastIndexOf(s.charAt(i));
}
System.out.println(" ");
}
}
Using Java 8 streams with groupingBy()
//way 1
String name = "anandha";
Map<Character,Long> map = name.chars()
.mapToObj(ch -> (char)ch)
.collect(Collectors.groupingBy(ch -> ch, Collectors.counting());
System.out.println(map);
using LinkedHashmap
//way2
String name = "anandha";
char[] charArray = name.toChararray();
Map<Character,Integer> map = new LinkedHashmap<>();
for(char ch: charArray)
{
if(map.containsKey(ch))
{
map.put(ch,map.get(ch)+1);
}else
{
map.put(ch,1)
}
}
map.foreach((key,value)->{
{
System.out.println(key +" : "+ value);
}
});
//(OR) iterate map using the way above or below
for(Map.Entry mp: map.entrySet())
{
System.out.println(mp.getKey()+" : "+ mp.getValue());
}
}
public static void main(String[] args) {
char[] array = "aabsbdcbdgratsbdbcfdgs".toCharArray();
char[][] countArr = new char[array.length][2];
int lastIndex = 0;
for (char c : array) {
int foundIndex = -1;
for (int i = 0; i < lastIndex; i++) {
if (countArr[i][0] == c) {
foundIndex = i;
break;
}
}
if (foundIndex >= 0) {
int a = countArr[foundIndex][1];
countArr[foundIndex][1] = (char) ++a;
} else {
countArr[lastIndex][0] = c;
countArr[lastIndex][1] = '1';
lastIndex++;
}
}
for (int i = 0; i < lastIndex; i++) {
System.out.println(countArr[i][0] + " " + countArr[i][1]);
}
}

Finding repeated words on a string and counting the repetitions

I need to find repeated words on a string, and then count how many times they were repeated. So basically, if the input string is this:
String s = "House, House, House, Dog, Dog, Dog, Dog";
I need to create a new string list without repetitions and save somewhere else the amount of repetitions for each word, like such:
New String: "House, Dog"
New Int Array: [3, 4]
Is there a way to do this easily with Java? I've managed to separate the string using s.split() but then how do I count repetitions and eliminate them on the new string? Thanks!
You've got the hard work done. Now you can just use a Map to count the occurrences:
Map<String, Integer> occurrences = new HashMap<String, Integer>();
for ( String word : splitWords ) {
Integer oldCount = occurrences.get(word);
if ( oldCount == null ) {
oldCount = 0;
}
occurrences.put(word, oldCount + 1);
}
Using map.get(word) will tell you many times a word occurred. You can construct a new list by iterating through map.keySet():
for ( String word : occurrences.keySet() ) {
//do something with word
}
Note that the order of what you get out of keySet is arbitrary. If you need the words to be sorted by when they first appear in your input String, you should use a LinkedHashMap instead.
Try this,
public class DuplicateWordSearcher {
#SuppressWarnings("unchecked")
public static void main(String[] args) {
String text = "a r b k c d se f g a d f s s f d s ft gh f ws w f v x s g h d h j j k f sd j e wed a d f";
List<String> list = Arrays.asList(text.split(" "));
Set<String> uniqueWords = new HashSet<String>(list);
for (String word : uniqueWords) {
System.out.println(word + ": " + Collections.frequency(list, word));
}
}
}
public class StringsCount{
public static void main(String args[]) {
String value = "This is testing Program testing Program";
String item[] = value.split(" ");
HashMap<String, Integer> map = new HashMap<>();
for (String t : item) {
if (map.containsKey(t)) {
map.put(t, map.get(t) + 1);
} else {
map.put(t, 1);
}
}
Set<String> keys = map.keySet();
for (String key : keys) {
System.out.println(key);
System.out.println(map.get(key));
}
}
}
As mentioned by others use String::split(), followed by some map (hashmap or linkedhashmap) and then merge your result. For completeness sake putting the code.
import java.util.*;
public class Genric<E>
{
public static void main(String[] args)
{
Map<String, Integer> unique = new LinkedHashMap<String, Integer>();
for (String string : "House, House, House, Dog, Dog, Dog, Dog".split(", ")) {
if(unique.get(string) == null)
unique.put(string, 1);
else
unique.put(string, unique.get(string) + 1);
}
String uniqueString = join(unique.keySet(), ", ");
List<Integer> value = new ArrayList<Integer>(unique.values());
System.out.println("Output = " + uniqueString);
System.out.println("Values = " + value);
}
public static String join(Collection<String> s, String delimiter) {
StringBuffer buffer = new StringBuffer();
Iterator<String> iter = s.iterator();
while (iter.hasNext()) {
buffer.append(iter.next());
if (iter.hasNext()) {
buffer.append(delimiter);
}
}
return buffer.toString();
}
}
New String is Output = House, Dog
Int array (or rather list) Values = [3, 4] (you can use List::toArray) for getting an array.
Using java8
private static void findWords(String s, List<String> output, List<Integer> count){
String[] words = s.split(", ");
Map<String, Integer> map = new LinkedHashMap<>();
Arrays.stream(words).forEach(e->map.put(e, map.getOrDefault(e, 0) + 1));
map.forEach((k,v)->{
output.add(k);
count.add(v);
});
}
Also, use a LinkedHashMap if you want to preserve the order of insertion
private static void findWords(){
String s = "House, House, House, Dog, Dog, Dog, Dog";
List<String> output = new ArrayList<>();
List<Integer> count = new ArrayList<>();
findWords(s, output, count);
System.out.println(output);
System.out.println(count);
}
Output
[House, Dog]
[3, 4]
If this is a homework, then all I can say is: use String.split() and HashMap<String,Integer>.
(I see you've found split() already. You're along the right lines then.)
It may help you somehow.
String st="I am am not the one who is thinking I one thing at time";
String []ar = st.split("\\s");
Map<String, Integer> mp= new HashMap<String, Integer>();
int count=0;
for(int i=0;i<ar.length;i++){
count=0;
for(int j=0;j<ar.length;j++){
if(ar[i].equals(ar[j])){
count++;
}
}
mp.put(ar[i], count);
}
System.out.println(mp);
Once you have got the words from the string it is easy.
From Java 10 onwards you can try the following code:
import java.util.Arrays;
import java.util.stream.Collectors;
public class StringFrequencyMap {
public static void main(String... args) {
String[] wordArray = {"House", "House", "House", "Dog", "Dog", "Dog", "Dog"};
var freq = Arrays.stream(wordArray)
.collect(Collectors.groupingBy(x -> x, Collectors.counting()));
System.out.println(freq);
}
}
Output:
{House=3, Dog=4}
You can use Prefix tree (trie) data structure to store words and keep track of count of words within Prefix Tree Node.
#define ALPHABET_SIZE 26
// Structure of each node of prefix tree
struct prefix_tree_node {
prefix_tree_node() : count(0) {}
int count;
prefix_tree_node *child[ALPHABET_SIZE];
};
void insert_string_in_prefix_tree(string word)
{
prefix_tree_node *current = root;
for(unsigned int i=0;i<word.size();++i){
// Assuming it has only alphabetic lowercase characters
// Note ::::: Change this check or convert into lower case
const unsigned int letter = static_cast<int>(word[i] - 'a');
// Invalid alphabetic character, then continue
// Note :::: Change this condition depending on the scenario
if(letter > 26)
throw runtime_error("Invalid alphabetic character");
if(current->child[letter] == NULL)
current->child[letter] = new prefix_tree_node();
current = current->child[letter];
}
current->count++;
// Insert this string into Max Heap and sort them by counts
}
// Data structure for storing in Heap will be something like this
struct MaxHeapNode {
int count;
string word;
};
After inserting all words, you have to print word and count by iterating Maxheap.
//program to find number of repeating characters in a string
//Developed by Subash<subash_senapati#ymail.com>
import java.util.Scanner;
public class NoOfRepeatedChar
{
public static void main(String []args)
{
//input through key board
Scanner sc = new Scanner(System.in);
System.out.println("Enter a string :");
String s1= sc.nextLine();
//formatting String to char array
String s2=s1.replace(" ","");
char [] ch=s2.toCharArray();
int counter=0;
//for-loop tocompare first character with the whole character array
for(int i=0;i<ch.length;i++)
{
int count=0;
for(int j=0;j<ch.length;j++)
{
if(ch[i]==ch[j])
count++; //if character is matching with others
}
if(count>1)
{
boolean flag=false;
//for-loop to check whether the character is already refferenced or not
for (int k=i-1;k>=0 ;k-- )
{
if(ch[i] == ch[k] ) //if the character is already refferenced
flag=true;
}
if( !flag ) //if(flag==false)
counter=counter+1;
}
}
if(counter > 0) //if there is/are any repeating characters
System.out.println("Number of repeating charcters in the given string is/are " +counter);
else
System.out.println("Sorry there is/are no repeating charcters in the given string");
}
}
public static void main(String[] args) {
String s="sdf sdfsdfsd sdfsdfsd sdfsdfsd sdf sdf sdf ";
String st[]=s.split(" ");
System.out.println(st.length);
Map<String, Integer> mp= new TreeMap<String, Integer>();
for(int i=0;i<st.length;i++){
Integer count=mp.get(st[i]);
if(count == null){
count=0;
}
mp.put(st[i],++count);
}
System.out.println(mp.size());
System.out.println(mp.get("sdfsdfsd"));
}
If you pass a String argument it will count the repetition of each word
/**
* #param string
* #return map which contain the word and value as the no of repatation
*/
public Map findDuplicateString(String str) {
String[] stringArrays = str.split(" ");
Map<String, Integer> map = new HashMap<String, Integer>();
Set<String> words = new HashSet<String>(Arrays.asList(stringArrays));
int count = 0;
for (String word : words) {
for (String temp : stringArrays) {
if (word.equals(temp)) {
++count;
}
}
map.put(word, count);
count = 0;
}
return map;
}
output:
Word1=2, word2=4, word2=1,. . .
import java.util.HashMap;
import java.util.LinkedHashMap;
public class CountRepeatedWords {
public static void main(String[] args) {
countRepeatedWords("Note that the order of what you get out of keySet is arbitrary. If you need the words to be sorted by when they first appear in your input String, you should use a LinkedHashMap instead.");
}
public static void countRepeatedWords(String wordToFind) {
String[] words = wordToFind.split(" ");
HashMap<String, Integer> wordMap = new LinkedHashMap<String, Integer>();
for (String word : words) {
wordMap.put(word,
(wordMap.get(word) == null ? 1 : (wordMap.get(word) + 1)));
}
System.out.println(wordMap);
}
}
I hope this will help you
public void countInPara(String str) {
Map<Integer,String> strMap = new HashMap<Integer,String>();
List<String> paraWords = Arrays.asList(str.split(" "));
Set<String> strSet = new LinkedHashSet<>(paraWords);
int count;
for(String word : strSet) {
count = Collections.frequency(paraWords, word);
strMap.put(count, strMap.get(count)==null ? word : strMap.get(count).concat(","+word));
}
for(Map.Entry<Integer,String> entry : strMap.entrySet())
System.out.println(entry.getKey() +" :: "+ entry.getValue());
}
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class DuplicateWord {
public static void main(String[] args) {
String para = "this is what it is this is what it can be";
List < String > paraList = new ArrayList < String > ();
paraList = Arrays.asList(para.split(" "));
System.out.println(paraList);
int size = paraList.size();
int i = 0;
Map < String, Integer > duplicatCountMap = new HashMap < String, Integer > ();
for (int j = 0; size > j; j++) {
int count = 0;
for (i = 0; size > i; i++) {
if (paraList.get(j).equals(paraList.get(i))) {
count++;
duplicatCountMap.put(paraList.get(j), count);
}
}
}
System.out.println(duplicatCountMap);
List < Integer > myCountList = new ArrayList < > ();
Set < String > myValueSet = new HashSet < > ();
for (Map.Entry < String, Integer > entry: duplicatCountMap.entrySet()) {
myCountList.add(entry.getValue());
myValueSet.add(entry.getKey());
}
System.out.println(myCountList);
System.out.println(myValueSet);
}
}
Input: this is what it is this is what it can be
Output:
[this, is, what, it, is, this, is, what, it, can, be]
{can=1, what=2, be=1, this=2, is=3, it=2}
[1, 2, 1, 2, 3, 2]
[can, what, be, this, is, it]
import java.util.HashMap;
import java.util.Scanner;
public class class1 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String inpStr = in.nextLine();
int key;
HashMap<String,Integer> hm = new HashMap<String,Integer>();
String[] strArr = inpStr.split(" ");
for(int i=0;i<strArr.length;i++){
if(hm.containsKey(strArr[i])){
key = hm.get(strArr[i]);
hm.put(strArr[i],key+1);
}
else{
hm.put(strArr[i],1);
}
}
System.out.println(hm);
}
}
Please use the below code. It is the most simplest as per my analysis. Hope you will like it:
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Scanner;
import java.util.Set;
public class MostRepeatingWord {
String mostRepeatedWord(String s){
String[] splitted = s.split(" ");
List<String> listString = Arrays.asList(splitted);
Set<String> setString = new HashSet<String>(listString);
int count = 0;
int maxCount = 1;
String maxRepeated = null;
for(String inp: setString){
count = Collections.frequency(listString, inp);
if(count > maxCount){
maxCount = count;
maxRepeated = inp;
}
}
return maxRepeated;
}
public static void main(String[] args)
{
System.out.println("Enter The Sentence: ");
Scanner s = new Scanner(System.in);
String input = s.nextLine();
MostRepeatingWord mrw = new MostRepeatingWord();
System.out.println("Most repeated word is: " + mrw.mostRepeatedWord(input));
}
}
package day2;
import java.util.ArrayList;
import java.util.HashMap;`enter code here`
import java.util.List;
public class DuplicateWords {
public static void main(String[] args) {
String S1 = "House, House, House, Dog, Dog, Dog, Dog";
String S2 = S1.toLowerCase();
String[] S3 = S2.split("\\s");
List<String> a1 = new ArrayList<String>();
HashMap<String, Integer> hm = new HashMap<>();
for (int i = 0; i < S3.length - 1; i++) {
if(!a1.contains(S3[i]))
{
a1.add(S3[i]);
}
else
{
continue;
}
int Count = 0;
for (int j = 0; j < S3.length - 1; j++)
{
if(S3[j].equals(S3[i]))
{
Count++;
}
}
hm.put(S3[i], Count);
}
System.out.println("Duplicate Words and their number of occurrences in String S1 : " + hm);
}
}
public class Counter {
private static final int COMMA_AND_SPACE_PLACE = 2;
private String mTextToCount;
private ArrayList<String> mSeparateWordsList;
public Counter(String mTextToCount) {
this.mTextToCount = mTextToCount;
mSeparateWordsList = cutStringIntoSeparateWords(mTextToCount);
}
private ArrayList<String> cutStringIntoSeparateWords(String text)
{
ArrayList<String> returnedArrayList = new ArrayList<>();
if(text.indexOf(',') == -1)
{
returnedArrayList.add(text);
return returnedArrayList;
}
int position1 = 0;
int position2 = 0;
while(position2 < text.length())
{
char c = ',';
if(text.toCharArray()[position2] == c)
{
String tmp = text.substring(position1, position2);
position1 += tmp.length() + COMMA_AND_SPACE_PLACE;
returnedArrayList.add(tmp);
}
position2++;
}
if(position1 < position2)
{
returnedArrayList.add(text.substring(position1, position2));
}
return returnedArrayList;
}
public int[] countWords()
{
if(mSeparateWordsList == null) return null;
HashMap<String, Integer> wordsMap = new HashMap<>();
for(String s: mSeparateWordsList)
{
int cnt;
if(wordsMap.containsKey(s))
{
cnt = wordsMap.get(s);
cnt++;
} else {
cnt = 1;
}
wordsMap.put(s, cnt);
}
return printCounterResults(wordsMap);
}
private int[] printCounterResults(HashMap<String, Integer> m)
{
int index = 0;
int[] returnedIntArray = new int[m.size()];
for(int i: m.values())
{
returnedIntArray[index] = i;
index++;
}
return returnedIntArray;
}
}
/*count no of Word in String using TreeMap we can use HashMap also but word will not display in sorted order */
import java.util.*;
public class Genric3
{
public static void main(String[] args)
{
Map<String, Integer> unique = new TreeMap<String, Integer>();
String string1="Ram:Ram: Dog: Dog: Dog: Dog:leela:leela:house:house:shayam";
String string2[]=string1.split(":");
for (int i=0; i<string2.length; i++)
{
String string=string2[i];
unique.put(string,(unique.get(string) == null?1:(unique.get(string)+1)));
}
System.out.println(unique);
}
}
//program to find number of repeating characters in a string
//Developed by Rahul Lakhmara
import java.util.*;
public class CountWordsInString {
public static void main(String[] args) {
String original = "I am rahul am i sunil so i can say am i";
// making String type of array
String[] originalSplit = original.split(" ");
// if word has only one occurrence
int count = 1;
// LinkedHashMap will store the word as key and number of occurrence as
// value
Map<String, Integer> wordMap = new LinkedHashMap<String, Integer>();
for (int i = 0; i < originalSplit.length - 1; i++) {
for (int j = i + 1; j < originalSplit.length; j++) {
if (originalSplit[i].equals(originalSplit[j])) {
// Increment in count, it will count how many time word
// occurred
count++;
}
}
// if word is already present so we will not add in Map
if (wordMap.containsKey(originalSplit[i])) {
count = 1;
} else {
wordMap.put(originalSplit[i], count);
count = 1;
}
}
Set word = wordMap.entrySet();
Iterator itr = word.iterator();
while (itr.hasNext()) {
Map.Entry map = (Map.Entry) itr.next();
// Printing
System.out.println(map.getKey() + " " + map.getValue());
}
}
}
public static void main(String[] args){
String string = "elamparuthi, elam, elamparuthi";
String[] s = string.replace(" ", "").split(",");
String[] op;
String ops = "";
for(int i=0; i<=s.length-1; i++){
if(!ops.contains(s[i]+"")){
if(ops != "")ops+=", ";
ops+=s[i];
}
}
System.out.println(ops);
}
For Strings with no space, we can use the below mentioned code
private static void findRecurrence(String input) {
final Map<String, Integer> map = new LinkedHashMap<>();
for(int i=0; i<input.length(); ) {
int pointer = i;
int startPointer = i;
boolean pointerHasIncreased = false;
for(int j=0; j<startPointer; j++){
if(pointer<input.length() && input.charAt(j)==input.charAt(pointer) && input.charAt(j)!=32){
pointer++;
pointerHasIncreased = true;
}else{
if(pointerHasIncreased){
break;
}
}
}
if(pointer - startPointer >= 2) {
String word = input.substring(startPointer, pointer);
if(map.containsKey(word)){
map.put(word, map.get(word)+1);
}else{
map.put(word, 1);
}
i=pointer;
}else{
i++;
}
}
for(Map.Entry<String, Integer> entry : map.entrySet()){
System.out.println(entry.getKey() + " = " + (entry.getValue()+1));
}
}
Passing some input as "hahaha" or "ba na na" or "xxxyyyzzzxxxzzz" give the desired output.
Hope this helps :
public static int countOfStringInAText(String stringToBeSearched, String masterString){
int count = 0;
while (masterString.indexOf(stringToBeSearched)>=0){
count = count + 1;
masterString = masterString.substring(masterString.indexOf(stringToBeSearched)+1);
}
return count;
}
package string;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class DublicatewordinanArray {
public static void main(String[] args) {
String str = "This is Dileep Dileep Kumar Verma Verma";
DuplicateString(str);
}
public static void DuplicateString(String str) {
String word[] = str.split(" ");
Map < String, Integer > map = new HashMap < String, Integer > ();
for (String w: word)
if (!map.containsKey(w)) {
map.put(w, 1);
}
else {
map.put(w, map.get(w) + 1);
}
Set < Map.Entry < String, Integer >> entrySet = map.entrySet();
for (Map.Entry < String, Integer > entry: entrySet)
if (entry.getValue() > 1) {
System.out.printf("%s : %d %n", entry.getKey(), entry.getValue());
}
}
}
Using Java 8 streams collectors:
public static Map<String, Integer> countRepetitions(String str) {
return Arrays.stream(str.split(", "))
.collect(Collectors.toMap(s -> s, s -> 1, (a, b) -> a + 1));
}
Input: "House, House, House, Dog, Dog, Dog, Dog, Cat"
Output: {Cat=1, House=3, Dog=4}
please try these it may be help for you.
public static void main(String[] args) {
String str1="House, House, House, Dog, Dog, Dog, Dog";
String str2=str1.replace(",", "");
Map<String,Integer> map=findFrquenciesInString(str2);
Set<String> keys=map.keySet();
Collection<Integer> vals=map.values();
System.out.println(keys);
System.out.println(vals);
}
private static Map<String,Integer> findFrquenciesInString(String str1) {
String[] strArr=str1.split(" ");
Map<String,Integer> map=new HashMap<>();
for(int i=0;i<strArr.length;i++) {
int count=1;
for(int j=i+1;j<strArr.length;j++) {
if(strArr[i].equals(strArr[j]) && strArr[i]!="-1") {
strArr[j]="-1";
count++;
}
}
if(count>1 && strArr[i]!="-1") {
map.put(strArr[i], count);
strArr[i]="-1";
}
}
return map;
}
as introduction of stream has changed the way we code; i would like to add some of the ways of doing this using it
String[] strArray = str.split(" ");
//1. All string value with their occurrences
Map<String, Long> counterMap =
Arrays.stream(strArray).collect(Collectors.groupingBy(e->e, Collectors.counting()));
//2. only duplicating Strings
Map<String, Long> temp = counterMap.entrySet().stream().filter(map->map.getValue() > 1).collect(Collectors.toMap(map -> map.getKey(), map -> map.getValue()));
System.out.println("test : "+temp);
//3. List of Duplicating Strings
List<String> masterStrings = Arrays.asList(strArray);
Set<String> duplicatingStrings =
masterStrings.stream().filter(i -> Collections.frequency(masterStrings, i) > 1).collect(Collectors.toSet());
Use Function.identity() inside Collectors.groupingBy and store everything in a MAP.
String a = "Gini Gina Gina Gina Gina Protijayi Protijayi ";
Map<String, Long> map11 = Arrays.stream(a.split(" ")).collect(Collectors
.groupingBy(Function.identity(),Collectors.counting()));
System.out.println(map11);
// output => {Gina=4, Gini=1, Protijayi=2}
In Python we can use collections.Counter()
a = "Roopa Roopi loves green color Roopa Roopi"
words = a.split()
wordsCount = collections.Counter(words)
for word,count in sorted(wordsCount.items()):
print('"%s" is repeated %d time%s.' % (word,count,"s" if count > 1 else "" ))
Output :
"Roopa" is repeated 2 times.
"Roopi" is repeated 2 times.
"color" is repeated 1 time.
"green" is repeated 1 time.
"loves" is repeated 1 time.

Categories

Resources