Get Hashmap Top 3 Keys - java

I have a hashmap storing the number of occurrences of character in a text. I am trying to print out the top 3 occurrences, but it is printing incorrectly.
int max = 1000000000;
for (int i = 1; i <= 3; i++) {
for (Character key : list.keySet()) {
if (list.get(key) < max) {
max = list.get(key);
System.out.println(i + ": " + key + " " + list.get(key));
break;
}
}
}

With Java 8 you can use the code below(*):
List<Entry<Character, Integer>> top3 = map.entrySet().stream()
.sorted(comparing(Entry::getValue, reverseOrder()))
.limit(3)
.collect(toList());
(*) with the following imports:
import static java.util.Comparator.comparing;
import static java.util.Comparator.reverseOrder;
import static java.util.stream.Collectors.toList;

You could modify your program to this form:
for (int i = 1; i <= 3; i++) {
int max = -1;
Character maxKey = 'a';
for (Character key : list.keySet()) {
if (list.get(key) > max) {
max = list.get(key);
maxKey = key;
}
}
System.out.println(i + ": " + maxKey + " " + max );
list.remove(maxKey);
}

You need to sort your entries by number of occurences and get the top 3:
List<Entry<Character, Integer>> entryList = new ArrayList<>(list.entrySet());
Collections.sort(entryList, new Comparator<Entry<Character, Integer>>(){
#Override
public int compare(Entry<Character, Integer> e1, Entry<Character, Integer> e2) {
return e2.getValue() - e1.getValue(); // descending order
}
});
// now let's get the top 3
List<Character> top3 = new ArrayList<>(3);
for(Entry<Character, Integer> e : entryList) {
top3.add(e.getValue());
if(top3.size() == 3) {
break;
}
}

Here's a solution using Java 8 streams, based on the one provided by #assylias. It performs the complete task of collecting character counts from a String into a Map and selecting the top 3 entries.
import java.util.ArrayList;
import static java.util.Comparator.*;
import java.util.List;
import java.util.Map.Entry;
import static java.util.stream.Collectors.*;
public class Stream {
public static void main(final String[] args) {
final String text = "hello stackoverflow, let's count these character occurrences!";
final char[] charArray = text.toCharArray();
final List<Character> characters = new ArrayList<Character>(text.length());
for (final char c : charArray) {
characters.add(c);
}
final List<Entry<Character, Long>> top3 = characters.stream()
.collect(groupingBy(Character::charValue, counting()))
.entrySet().stream()
.sorted(comparing(Entry::getValue, reverseOrder())).limit(3).collect(toList());
System.out.println(top3);
}
}
Output:
[e=8, c=7, =6]

Related

Count occurrences & print highest occurred char 'n' times

I was trying to solve some programs, I came across this interesting one, where we need to print the highest occurred character n times & likewise for other characters.
Ex: Input string : "please stay hydrated"
Output string : "aaaeeettyysplhdr"
I was only able to solve half way, where we print the highest occurred character & the times it has occurred using a HashMap.
public static void repeatedChar(String str) {
char[] chars = str.toCharArray();
Map<Character, Integer> map = new HashMap<>();
for (Character c : chars) {
if (map.containsKey(c)) {
map.put(c, map.get(c) + 1);
} else {
map.put(c, 1);
}
}
//Now To find the highest character repeated
int max = 0;
//setting to a by default
char maxCharacter = 'a';
for (Map.Entry<Character, Integer> entry : map.entrySet()) {
System.out.println("Key = " + entry.getKey() + ": Value " + entry.getValue());
if (max < entry.getValue()) {
max = entry.getValue();
maxCharacter = entry.getKey();
}
}
System.out.println("Max Character = " + maxCharacter + " Max Count : " + max);
}
This currently prints the highest occured character & the number of times that character has occurred. Can someone please let me know how to proceed further? Thanks
In order to get the desired output you need to sort your map by value. But since a hashmap is not meant to be sorted, but accessed fast, you could add all entries to a list and sort the list. Something like:
import java.util.Map.Entry;
import java.util.Comparator;
....
public static void repeatedChar(String str) {
char[] chars = str.toCharArray();
Map<Character, Integer> map = new HashMap<>();
for (Character c : chars) {
if (map.containsKey(c)) {
map.put(c, map.get(c) + 1);
} else {
map.put(c, 1);
}
}
//add map entries to list
List<Entry<Character, Integer>> list = new ArrayList<>(map.entrySet());
//sort entries by value descending
list.sort(Entry.comparingByValue(Comparator.reverseOrder()));
//print
for (Entry<Character, Integer> entry : list) {
for (int i = 0; i < entry.getValue(); i++){
System.out.print(entry.getKey());
}
}
}
and if you fancy a stream approach:
import java.util.Comparator;
import java.util.Map;
import java.util.function.Function;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
....
public static void repeatedCharWithStreams(String str) {
String output =
Pattern.compile("")
.splitAsStream(str)
.collect(Collectors.groupingBy(Function.identity(),Collectors.counting()))
.entrySet().stream()
.sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
.map(e -> e.getKey().repeat(e.getValue().intValue()))
.collect(Collectors.joining());
System.out.println(output);
}

A program that counts the letters in string in Java

I have to create a program that counts the letters in string and I have a little problem with that.
This is my code in main:
Scanner sc = new Scanner(System.in);
String str;
int count;
System.out.println("Enter some text: ");
str = sc.nextLine();
char ch;
System.out.println("Letters: ");
for (ch = (char) 65; ch <= 90; ch++) {
count = 0;
for (int i = 0; i < str.length(); i++) {
if (ch == str.charAt(i) || (ch + 32) == str.charAt(i)) {
count++;
}
}
if (count > 0) {
System.out.println(ch + ": " + count);
}
}
Everything looks fine, but the output should not be in alphabetical order, rather ordered by the number of letters descending.
For example, if you input Hello World, the output should be something like this:
L: 3
O: 2
H: 1
D: 1
E: 1
R: 1
W: 1
The output would be sorted in descending order of letter frequency. That means the most frequent letter should appear first and the least last.
The order for letters that appears in equal proportions must be in alphabetical order.
The problem is that your outer loop browse the letters in alphabetical order, and that's where you display the count.
I would instead recommend browsing the input string with a single loop, updating the count of each letter in a Map<Character, Integer> as I encounter them.
Then once the input String has been consumed, I would sort the Map by descending values, and print each key/value pair.
Map<Character, Integer> lettersCount = new HashMap<>();
for (int i=0; i <str.length(); i++) {
Character current = str.charAt(i);
if (Character.isLetter(current)) {
Integer previousCount = lettersCount.get(current);
if (previousCount != null) {
lettersCount.put(current, previousCount + 1);
} else {
lettersCount.put(current, 1);
}
}
}
List<Map.Entry<Character, Integer>> list = new LinkedList<Map.Entry<Character, Integer>>( lettersCount.entrySet() );
Collections.sort( list, new Comparator<Map.Entry<Character, Integer>>()
{
public int compare( Map.Entry<Character, Integer> o1, Map.Entry<Character, Integer> o2 )
{
return (o2.getValue()).compareTo( o1.getValue() );
}
} );
for (Map.Entry<Character, Integer> entry : list) {
System.out.println(entry.getKey() + " : " + entry.getValue());
}
You can try it out on ideone.
As you can see, sorting a Map by values isn't trivial :-/
If you want to sort the results then you'll have to store the results & then iterate over them by their count descending to print in order
The best data structure to store them into would be a heap, keyed off of count. Java supplies such a data structure as java.util.PriorityQueue which can take a comparator function which first compares count & then character
https://docs.oracle.com/javase/7/docs/api/java/util/PriorityQueue.html
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str;
int count;
System.out.println("Enter some text: ");
str = sc.nextLine();
char ch;
System.out.println("Letters: ");
LinkedHashMap<String, Integer> charCountMap = new LinkedHashMap<String, Integer>();
for (ch = (char) 65; ch <= 90; ch++) {
count = 0;
for (int i = 0; i < str.length(); i++) {
if (ch == str.charAt(i) || (ch + 32) == str.charAt(i)) {
count++;
}
}
if (count > 0) {
System.out.println(ch + ": " + count);
charCountMap.put(ch + "", count);
}
}
LinkedHashMap<String, Integer> sortedMapBasedOnValues = sortHashMapByValues(charCountMap);
for (Map.Entry<String, Integer> entry : sortedMapBasedOnValues.entrySet()) {
System.out.println("Key : " + entry.getKey() + " Value : " + entry.getValue());
}
}
// Following method used from
// http://stackoverflow.com/questions/8119366/sorting-hashmap-by-values
public static LinkedHashMap<String, Integer> sortHashMapByValues(LinkedHashMap<String, Integer> passedMap) {
List<String> mapKeys = new ArrayList<>(passedMap.keySet());
List<Integer> mapValues = new ArrayList<>(passedMap.values());
Collections.sort(mapValues, Collections.reverseOrder());
Collections.sort(mapKeys);
LinkedHashMap<String, Integer> sortedMap = new LinkedHashMap<>();
Iterator<Integer> valueIt = mapValues.iterator();
while (valueIt.hasNext()) {
Integer val = valueIt.next();
Iterator<String> keyIt = mapKeys.iterator();
while (keyIt.hasNext()) {
String key = keyIt.next();
Integer comp1 = passedMap.get(key);
Integer comp2 = val;
if (comp1.equals(comp2)) {
keyIt.remove();
sortedMap.put(key, val);
break;
}
}
}
return sortedMap;
}
}

First Non Repeating Character using hashmap in one loop?

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);
}
}

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.

Hashmap implementation to count the occurrences of each character

The below code is to count the occurence of each character and it should print the count.
But with the code I have tried I get only a 1 I don't know the changes I should make.
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
class Count_CharMap {
public static void main(String[] args) {
try
{
FileInputStream file = new FileInputStream("D:\\trial.txt");
DataInputStream dis = new DataInputStream(file);
BufferedReader br = new BufferedReader(new InputStreamReader(dis));
String Contents="";
String str="";
while ((Contents = br.readLine()) != null) {
str+=Contents;
}
char[]char_array =str.toCharArray();
int count = 0;
char ch = char_array[count];
Map<Character,Integer> charCounter=new HashMap<Character,Integer>();
for(int i=0;i<str.length();i++)
{
if(charCounter.containsKey(char_array[i]))
{
charCounter.put(ch, charCounter.get(ch)+1);
}
else
{
charCounter.put(ch, 1);
}
}
for(Character key:charCounter.keySet())
{
System.out.println(key+""+charCounter.get(key));
}
}
catch(IOException e1){
System.out.println(e1);
}
}
}
Actual output should be like
If i have abcdabc in my trial.txt it should print a 2 b 2c 2 d 1.
You're leaving char ch set as the same character through each execution of the loop.
It should be:
ch = char_array[i];
if(charCounter.containsKey(ch)){
charCounter.put(ch, charCounter.get(ch)+1);
}
else
{
charCounter.put(ch, 1);
}
Inside the for loop.
Java 8 streams:
Map<String, Long> map =
Arrays.stream(string.split("")).
collect(Collectors.groupingBy(c -> c, Collectors.counting()));
Guava HashMultiset:
Multiset<Character> set = HashMultiset.create(Chars.asList("bbc".toCharArray()));
assertEquals(2, set.count('b'));
Hai All The below code is to count the occurrence of each character and it should print the count. may be helps you..Thanks for seeing
package com.corejava;
import java.util.Map;
import java.util.TreeMap;
public class Test {
public static void main(String[] args) {
String str = "ramakoteswararao";
char[] char_array = str.toCharArray();
System.out.println("The Given String is : " + str);
Map<Character, Integer> charCounter = new TreeMap<Character, Integer>();
for (char i : char_array) {
charCounter.put(i,charCounter.get(i) == null ? 1 : charCounter.get(i) + 1);
}
for (Character key : charCounter.keySet()) {
System.out.println("occurrence of '" + key + "' is "+ charCounter.get(key));
}
}
}
import java.util.HashMap;
import java.util.Map;
...
Map<String, Integer> freq = new HashMap<String, Integer>();
...
int count = freq.containsKey(word) ? freq.get(word) : 0;
freq.put(word, count + 1);
inside the for loop
ch = char_array[i];
charCounter.put(charCounter.contains(ch)?charCounter.get(ch)+1:1);
import java.util.TreeMap;
public class OccuranceDemo {
public static void main(String[] args) {
TreeMap<String , Integer> mp=new TreeMap();
String s="rain rain go away";
String[] arr = s.split(" ");
int length=arr.length;
for(int i=0;i<length;i++)
{
String h = arr[i];
mp.put(h, mp.get(h)==null?1:mp.get(h)+1);
}
System.out.println(mp.get("go"));
}
}
String str=new String("aabbbcddddee");
char[] ch=str.toCharArray();
HashMap<Character,Integer> hm=new HashMap<Character,Integer>();
for(char ch1:ch)
{
if(hm.containsKey(ch1))
{
hm.put(ch1,hm.get(ch1)+1);
}
else
{
hm.put(ch1,1);
}
}
Set s1=hm.entrySet();
Iterator itr=s1.iterator();
while(itr.hasNext())
{
Map.Entry m1=(Map.Entry)itr.next();
System.out.println(m1);
}
import java.util.*;
public class Test {
public static void main(String[] args) {
String str = "STACKOVERFLOW";
char[] char_array = str.toCharArray();
System.out.println("The Given String is : " + str);
Map<Character, Integer> charCounter = new TreeMap<Character, Integer>();
for (char i : char_array) {
charCounter.put(i,charCounter.get(i) == null ? 1 : charCounter.get(i) + 1);
}
for (Character key : charCounter.keySet()) {
System.out.println("occurrence of '" + key + "' is "+ charCounter.get(key));
}
}
}
public void mapPractices() {
Map<Character, Integer> map = new HashMap<>();
String dataString = "!##$%^&*()__)(*&^%$##!##$%^&*(*&^%$##!##$%^&*()(*&^%$##!##$%^&*()(*&^%$##!##$%^&*()(*&^%$#";
for (int i = 0; i < dataString.length(); i++) {
char charAt = dataString.charAt(i);
if (map.containsKey(charAt)) {
int val = map.get(charAt);
map.put(charAt, val+1);
} else {
map.put(charAt, +1);
}
}
System.out.println("Characters ant the string=" + map);
}
a lambda one-liner
After the bug in the old-school-solution is fixed, here is an alternative solution in lambda that does the same thing:
Map<Character,Long> counts =
"an example string to work with".codePoints().boxed().collect(
groupingBy( t -> (char)(int)t, counting() ) );
gets: { =5, a=2, e=2, g=1, h=1, i=2, k=1, l=1, m=1, n=2, o=2, p=1, r=2, s=1, t=3, w=2, x=1}
You can get the number of a specific character eg. 't' by:
counts.get( 't' )
(I also write a lambda solution out of morbid curiosity to find out how slow my solution is, preferably from the guy with the 10-line solution.)

Categories

Resources