How to take for loop output to separate array in Java? - java

I need to take following code output to separate array for use another calculation. In this example output is,
z count is= 1
y count is= 3
x count is= 2.
I need to take 1, 3, 2 to separate array. How I do it? I am new to Java.
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class ForArrays {
public static void main(String[] args) {
ArrayList<String> name = new ArrayList<String>();
HashMap<String, Integer> termFreqMap = new HashMap<String, Integer>();
ArrayList<String> words = new ArrayList<String>();
HashMap<String, Integer> wordFreqMap = new HashMap<String, Integer>();
name.add("x");
name.add("y x");
name.add("y z y");
// count words
for (int j = 0; j < name.size(); j++) {
String tempname = name.get(j);
String[] result = tempname.split(" ");
for (String s : result) {
Integer twf = wordFreqMap.get(s);
if (twf == null)
wordFreqMap.put(s, new Integer(1));
else {
wordFreqMap.put(s, new Integer(++twf));
}
}
}
for (Map.Entry<String, Integer> entry : wordFreqMap.entrySet()) {
String tempWord = entry.getKey();
Integer wf = entry.getValue();
System.out.println(tempWord + " " + "count is= " + wf);
}
}
}

Create a int array with the size of the Hashmap so that both hashmap size and array size will be similar. And while iterating the Hashmap save the result in array.
The catch with this is hashmap doesn't have insertion order so the array will not be in insertion order.So you may not know the count is for what key.For that you can create one keys array and put the keys also there for one to one mapping of keys array and countarray.
int countArray[] = new int[wordFreqMap.size()];
int i=0;
for (Map.Entry<String, Integer> entry : wordFreqMap.entrySet()) {
String tempWord = entry.getKey();
Integer wf = entry.getValue();
System.out.println(tempWord + " " + "count is= " + wf);
countArray[i++] = wf;
}

Related

Filter 2d array by Hashmap key and value

I have a String[][] array and a HashMap<String, Integer>
String[][] array = {{"name1", "field1"}, {"name2", "field2"}, {"name3", "field1"}};
Map<String, Integer> map = new HashMap<>();
map.put("field1", Integer1);
map.put("field2", Integer2);
From this i need to get an array of first Integer1 names + first Integer2 names if array[i][1] i.e. field equals map.getValue() i.e. field)
so for Integer1 = Integer2 = 1
the answer is {name1, name2)
for Integer1 = 2, Integer2 = 1
the answer is {name1, name2, name3}
Allways Integer1 <= rows with field1 Integer2 <= rows with field2
the only thing i could do is horrible tripple cycle which is not even properly working
the input is
n lines of strings
profession,number_of_employees_required
m lines of strings
name,profession,points1,points2
so i've decided to make a n-size HashMap<String, Integer>
and m*4-size String[][] array because i need it to be sorted is descending order via points1 and in ascending order via points2, so i've sorted the array[][] in needed way and now i need to get number_of_employees_required names from that array for each profession
i make input from .txt file which looks like this
2
developer,1
project,1
3
Bill,developer,6,100
John,developer,5,0
Steve,project,6,10
the answer is [Bill, Steve]
if input is
2
developer,2
project,1
3
Bill,developer,6,100
John,developer,5,0
Steve,project,6,10
the answer should be [Bill, John, Steve]
My code is:
public class Main {
public static void main(String[] args) throws FileNotFoundException {
solution();
}
public static void solution() throws FileNotFoundException {
Scanner sc = new Scanner(new File("input.txt"));
Map<String, AtomicInteger> hm = new HashMap<>();
int n = sc.nextInt();
for (int i = 0; i < n; i++) {
String line = sc.next();
hm.put(line.substring(0, line.indexOf(",")),
new AtomicInteger(Integer.parseInt(line.substring(line.indexOf(",") + 1))));
}
System.out.println(hm);
int k = sc.nextInt();
String[][] candidates = new String[k][4];
for (int i = 0; i < k; i++) {
candidates[i] = sc.next().split(",");
}
Arrays.sort(candidates, (o1, o2) -> {
if (Integer.parseInt(o2[2]) == Integer.parseInt(o1[2])) {
return Integer.parseInt(o1[3]) - Integer.parseInt(o2[3]);
} else {
return Integer.parseInt(o2[2]) - Integer.parseInt(o1[2]);
}
});
System.out.println(Arrays.deepToString(candidates));
Set<String> res = new TreeSet<>();
for (String[] candidate : candidates) {
for(Map.Entry<String, AtomicInteger> entry : hm.entrySet()) {
while (entry.getKey().equals(candidate[1]) && entry.getValue().intValue() > 0){
res.add(candidate[0]);
entry.getValue().decrementAndGet();
}
}
}
System.out.println(res);
}
}
It doesnt work when i make second input the answer is still [Bill, Steve]
I tried to use atomicIntegers to decrement HashMap value without hm.put(key, hm.get(key) - 1) thing

Find index pairs in array whose value sum is equal to given sum

I have a method which accepts two parameters. 1st is an integer array and 2nd is an integer.
The method should print the index pairs where sum of the values present in those indexes equal to the 2nd input parameter.
The brute force approach is to have two loops which will take O(n^2) time. But I need to solve this in O(n) time.
The array can have repetitions and can have negative numbers also.
If it prints one pair then the reverse pair is not allowed. For example in the below sample if it should not print (4,0), (3,2), (5,3)
int[] arr = {3,4,-1,6,2,-1};
int sum = 5;
The method signature is :findPairs(int[] arr, int sum);
The output of this method will be : (0,4), (2,3), (3,5)
Explanation:
Element present at index 0 + Element present at index 4 = 3+2 = 5
Element present at index 2 + Element present at index 3 = -1+6 = 5
Element present at index 3 + Element present at index 5 = 6+-1 = 5
To clarify some confusions, I have tried using HashMap<Integer, List<Integer>>. Here, key is the elements of array and value is their respective indices. As repetition is allowed, so for a given element there can be multiple index locations. So value in the map is a list.
Your approach is absolutely correct.
Using Map does solve this problem in O(n).
We will capitalise the benefits provided to us by JAVA by making use of TreeMap in this case. (Not necessary to be used).
Also, the problem of repeated pairs of indices in the final answer can be solved using a visited map. This map checks if I have visited the particular index before. If yes, then I will not include it in my answer.
Have a look the implementation below:
import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;
public class Solution {
private static SortedMap<Integer, List<Integer>> map = new TreeMap<Integer, List<Integer>>();
private static final Scanner scanner = new Scanner(System.in);
String findPairs(int[] arr, int sum){
for(int i=0;i<arr.length;i++){
List<Integer> indexList = map.get(arr[i]);
if(indexList == null){
List<Integer> newIndexList = new ArrayList<Integer>();
newIndexList.add(i);
map.put(arr[i], newIndexList);
}else{
indexList.add(i);
}
}
Set s = map.entrySet();
HashMap<Integer, Boolean> visited = new HashMap<Integer, Boolean>();
// Using iterator in SortedMap
Iterator it = s.iterator();
String finalOutput = "";
while (it.hasNext())
{
Map.Entry m = (Map.Entry)it.next();
int key = (Integer)m.getKey();
List<Integer> indexList1 = (List<Integer>)m.getValue();
if(map.containsKey(sum-key)){
List<Integer> indexList2 = (List<Integer>)map.get(sum-key);
for(int i=0;i<indexList1.size();i++){
if(!visited.containsKey(indexList1.get(i))){
for(int j=0;j<indexList2.size();j++){
if(!(finalOutput.equals("") || finalOutput==null)){
finalOutput += ", ";
}
finalOutput += "(" + indexList1.get(i) + "," + indexList2.get(j) + ")";
visited.put(indexList2.get(j), true);
}
visited.put(indexList1.get(i), true);
}
}
}
}
return finalOutput;
}
public static void main(String[] args) throws IOException {
int[] arr = {3,4,-1,6,2,-1};
int sum = 5;
Solution obj = new Solution();
System.out.println(obj.findPairs(arr, sum));
}
}
Kindly feel free to ask doubts.
public HashMap<Integer, ArrayList<List<Integer>>> getPairs(int[] input, int targetSum) {
HashMap<Integer, ArrayList<List<Integer>>> hashMapList = new HashMap<Integer, ArrayList<List<Integer>>>();
for(int i=0;i< input.length;i++) {
//int j=i+1;
for(int j=1;j< input.length;j++) {
//if(j < input.length && input[i] + input[j] == targetSum ) {
if(i != j && input[i] + input[j] == targetSum ) {
ArrayList<List<Integer>> indexPairList = new ArrayList<List<Integer>>();
List<Integer> listPairs = new ArrayList<Integer>();
if( null != hashMapList.get(targetSum)) {
indexPairList = hashMapList.get(targetSum);
for(List<Integer> listPair : indexPairList) {
listPairs.addAll(listPair);
}
}
//System.out.println("listPairs - "+listPairs);
if(!listPairs.contains(i)
|| (!listPairs.contains(j))) {
List<Integer> pair = new ArrayList<Integer>();
pair.add(i);
pair.add(j);
indexPairList.add(pair);
hashMapList.put(targetSum, indexPairList);
}
}
}
}
return hashMapList;
}

Sorting string occurrences from text file

I have stored strings from a file into an ArrayList, and used a HashSet to count the number of occurrences of each string.
I am looking to list the top 5 words and their number of occurrences. I should be able to accomplish this w/o implementing a hashtable, treemap, etc. How can I go about achieving this?
Here is my ArrayList:
List<String> word_list = new ArrayList<String>();
while (INPUT_TEXT1.hasNext()) {
String input_word = INPUT_TEXT1.next();
word_list.add(input_word);
}
INPUT_TEXT1.close();
int word_list_length = word_list.size();
System.out.println("There are " + word_list_length + " words in the .txt file");
System.out.println("\n\n");
System.out.println("word_list's elements are: ");
for (int i = 0; i<word_list.size(); i++) {
System.out.print(word_list.get(i) + " ");
}
System.out.println("\n\n");
Here is my HashSet:
Set<String> unique_word = new HashSet<String>(word_list);
int number_of_unique = unique_word.size();
System.out.println("unique worlds are: ");
for (String e : unique_word) {
System.out.print(e + " ");
}
System.out.println("\n\n");
String [] word = new String[number_of_unique];
int [] freq = new int[number_of_unique];
int count = 0;
System.out.println("Frequency counts : ");
for (String e : unique_word) {
word[count] = e;
freq[count] = Collections.frequency(word_list, e);
System.out.println(word[count] + " : "+ freq[count] + " time(s)");
count++;
}
Could it be that I am overthinking a step? Thanks in advance
You can do this using HashMap (holds with unique word as key and frequency as value) and then sorting the values in the reverse order as explained in the below steps:
(1) Load the word_list with the words
(2) Find the unique words from word_list
(3) Store the unique words into HashMap with unique word as key and frequency as value
(4) Sort the HashMap with value (frequency)
You can refer the below code:
public static void main(String[] args) {
List<String> word_list = new ArrayList<>();
//Load your words to the word_list here
//Find the unique words now from list
String[] uniqueWords = word_list.stream().distinct().
toArray(size -> new String[size]);
Map<String, Integer> wordsMap = new HashMap<>();
int frequency = 0;
//Load the words to Map with each uniqueword as Key and frequency as Value
for (String uniqueWord : uniqueWords) {
frequency = Collections.frequency(word_list, uniqueWord);
System.out.println(uniqueWord+" occured "+frequency+" times");
wordsMap.put(uniqueWord, frequency);
}
//Now, Sort the words with the reverse order of frequency(value of HashMap)
Stream<Entry<String, Integer>> topWords = wordsMap.entrySet().stream().
sorted(Map.Entry.<String,Integer>comparingByValue().reversed()).limit(5);
//Now print the Top 5 words to console
System.out.println("Top 5 Words:::");
topWords.forEach(System.out::println);
}
Using java 8 and putting all code in one block.
Stream<Map.Entry<String,Long>> topWords =
words.stream()
.map(String::toLowerCase)
.collect(groupingBy(identity(), counting()))
.entrySet().stream()
.sorted(Map.Entry.<String, Long> comparingByValue(reverseOrder())
.thenComparing(Map.Entry.comparingByKey()))
.limit(5);
Iterate over stream
topWords.forEach(m -> {
System.out.print(m.getKey() + " : "+ m.getValue() + "time(s)");
});

To print the first biggest and second biggest elements in a string

Below is the code I have implemented. My doubt here is: when I am trying to print the first biggest and second Biggest values in the string, the output I get is in the order of [second biggest, first biggest].
Here is the output of what I got for the below code:
The output of the map is: real--6
The output of the map is: to--2
The output of the map is: world--1
The output of the map is: hello--0
The list after insertion is: [to, real]
The list inserted as [biggest,secondBiggest] after calling main is: [to, real]
......
but, I want The list after insertion to be: [real, to].
public class ReadString {
static String input = "This is a real project with real code to do real things to solve real problems in real world real";
public static void main(String[] args) {
List<String> lst = ReadString.RepeatedString("This is a real project with real "
+ "code to do real things to solve real " + "problems in real world real");
System.out.println("The list inserted as [biggest,secondBiggest] after calling main is: " + lst);
}
public static List<String> RepeatedString(String s) {
String[] s2 = input.split(" ");
String[] key = { "real", "to", "world", "hello" };
int count = 0;
Integer biggest = 0;
Integer secondBiggest = 1;
Map<String, Integer> map = new HashMap<String, Integer>();
for (int j = 0; j < key.length; j++) {
count = 0;
for (int i = 0; i < s2.length; i++) {
if (s2[i].equals(key[j])) {
count++;
}
}
map.put(key[j], count);
System.out.println("The output of the map is: " +key[j] + "--" + count);
}
/*
* To find the top two most repeated values.
*/
List<Integer> values = new ArrayList<Integer>(map.values());
Collections.sort(values);
for (int n : map.values()) {
if (biggest < n) {
secondBiggest = biggest;
biggest = n;
} else if (secondBiggest < n)
secondBiggest = n;
}
/* To get the top most repeated strings. */
List<String> list = new ArrayList<String>();
for (String s1 : map.keySet()) {
if (map.get(s1).equals(biggest))
list.add(s1);
else if (map.get(s1).equals(secondBiggest))
list.add(s1);
}
System.out.println("The list after insertion is: " +list);
return list;
}
}
The problem appears to be when you are adding items to the list. As you are iterating through the map.keySet(), there is no guarantee that you will get the biggest item first. The smallest change I would make would be to add the biggest item first in the list.
for (String s1 : map.keySet()) {
if (map.get(s1).equals(biggest))
list.add(0, s1);
else if (map.get(s1).equals(secondBiggest))
list.add(s1);
}
This way, if secondBiggest is added first, biggest will be at the top of the list.
We can simplify your approach quite a bit if we extract the word and count into a simple POJO. Something like,
static class WordCount implements Comparable<WordCount> {
String word;
int count;
WordCount(String word, int count) {
this.word = word;
this.count = count;
}
#Override
public int compareTo(WordCount o) {
return Integer.compare(count, o.count);
}
}
Then we can use that in repeatedString. First, count the words in the String; then build a List of WordCount(s). Sort it (since it's Comparable it has natural ordering). Then build the List to return by iterating the sorted List of WordCount(s) in reverse (for two items). Like,
static List<String> repeatedString(String s) {
Map<String, Integer> map = new HashMap<>();
for (String word : s.split("\\s+")) {
map.put(word, !map.containsKey(word) ? 1 : 1 + map.get(word));
}
List<WordCount> al = new ArrayList<>();
for (Map.Entry<String, Integer> entry : map.entrySet()) {
al.add(new WordCount(entry.getKey(), entry.getValue()));
}
Collections.sort(al);
List<String> ret = new ArrayList<>();
for (int i = al.size() - 1; i >= al.size() - 2; i--) {
ret.add(al.get(i).word);
}
return ret;
}
Finally, your main method should use your static input (or static input should be removed)
static String input = "This is a real project with real code to do "
+ "real things to solve real problems in real world real";
public static void main(String[] args) {
List<String> lst = repeatedString(input);
System.out.println("The list inserted as [biggest,"
+ "secondBiggest] after calling main is: " + lst);
}
And I get (as requested)
The list inserted as [biggest,secondBiggest] after calling main is: [real, to]
If you are only concerned about biggest and secondbiggest,
you can refer to the code below.
Instead of creating the list directly, I created an array, added required elements on specified positions. (This way it becomes more readable)
and finally convert the array to a list.
/* To get the top most repeated strings. */
String[] resultArray = new String[2];
for (String s1 : map.keySet()) {
if (map.get(s1).equals(biggest))
resultArray[0]=s1;
else if (map.get(s1).equals(secondBiggest))
resultArray[1]=s1;
}
List<String> list = Arrays.asList(resultArray);

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