I have four strings, string1, string2, string3 and string4. Two of these strings are equal, now I want to find out which are equal and put the result into two strings, e.g. result1="3" result2="4" if string 3 and 4 are equal. Of course I can do an if then else ladder
Code:
if(string1.equalsIgnoreCase(string2))
{
result1="1";
result2="2";
}
else if(string1.equalsIgnoreCase(string3))
{
result1="1";
result2="3";
}
//and so on
Is there a better way of doing this? result1 can be given as a string as above or as well as an integer if that makes it easier.
Having 4 strings the above code can handle it, but what if I have a 100 strings.
Yes, there is a better way. You could be using either a String array, or an ArrayList of type String. Then you could be comparing the values in a loop (or multiple loops) and assigning the value of the result in there with only having one or two conditional if statements. This would allow you to have any number of strings that are comparable.
May be we can convert the given strings to an integer using a hash function and compare only those strings whose hash values are same. Thinking in these lines may help reach an optimal solution
You could use a HashSet and add one string at a time. Before you add each string call the set's contains() method to see if it is already there. If it is you've found your match, if not you add the string and try the next one.
/**
* The purpose of this class is to find the frequency of each string in a text document. As of now, the text file is
* restricted to one line
*
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
try {
FileReader fr = new FileReader("D:/textDoc.txt");
BufferedReader br = new BufferedReader(fr);
String[] line = br.readLine().split("[ ,\\.]");
/*
* Put string and frequency as key-value pairs in a hash map
*/
Map map = null;
for (String s : line) {
if (s != null && s.trim()!="") {
if (map == null) {
map = new HashMap();
map.put(s, 1);
} else {
int value = map.containsKey(s) ? ((Integer) map.get(s) + 1) : 1;
map.put(s, value);
}
}
}
Set set = map.keySet();
Iterator iter = set.iterator();
while (iter.hasNext()) {
String s = (String) iter.next();
System.out.println("String: " + s + "\t frequency: " + map.get(s));
}
Bookmarks