I have searched for this on stackoverflow and found unrelated threads for this case. I have also tried on my own, and will keep trying until the solution. But it will be good if someone shows me if i am doing any mistakes in code.
I am having a HashSet so that i can keep away duplicate strings from being getting added to it. And if HashSet is adding then it must be a unique string.
My class declarations are :
public List<String> ContactsList;
public List<String> ContactsNumbersList;
My code to fetch contacts and adding it into these two lists by taking help of HashSet so that i keep duplicate numbers away is :
ContactsList = new ArrayList<String>();
ContactsNumbersList = new ArrayList<String>();
HashSet<String> normalizedNumbersAlreadyFound = new HashSet<>();
// Contacts Database queries
Cursor cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, new String[] {ContactsContract.CommonDataKinds.Phone._ID, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone.NUMBER}, null, null, ContactsContract.CommonDataKinds.Phone.SORT_KEY_PRIMARY +" ASC");
while (cursor.moveToNext())
{
String name = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
if (normalizedNumbersAlreadyFound.add(phoneNumber))
{
phoneNumber = phoneNumber.replace("-","");
phoneNumber = phoneNumber.replace(" ","");
phoneNumber = phoneNumber.replace("(","");
phoneNumber = phoneNumber.replace(")","");
ContactsList.add(name);
ContactsNumbersList.add(phoneNumber);
}
}
cursor.close();
Well then why my ContactsNumbersList having duplicate entries...? Thanking you in advance for any suggestions.. which will help me.
There seems to be a problem with your design.
First and foremost, you don't need Lists if your goal is to use a collection without duplicates.
Just use your Set instead.
Secondly, and specifically to your code, you are checking whether the element is added to your Set before normalizing it and adding the normalized String to the List.
Therefore, it may very well be that your List will contain duplicates because two elements that differ before normalization may be equal after normalization.
This leads me back to advise you to use your Set directly and disregard using a List in this use case.
Example
List<String> source = Arrays.asList("123-456789", "(1)23456789");
System.out.printf("Source List contains: %s%n", source);
Set<String> set = new HashSet<>();
List<String> unnecessary = new ArrayList<>();
Set<String> useful = new HashSet<>();
for (String s: source) {
if (set.add(s)) System.out.printf("Added %s to set.%n", s);
s = s.replaceAll("[()-]", "");
System.out.printf("\t... now normalized to %s%n", s);
// s is now normalized
unnecessary.add(s);
useful.add(s);
}
System.out.printf(
"Set contains %s.%nUnnecessary List contains %s.%nUseful Set contains %s.%n",
set,
unnecessary,
useful
);
Output
Source List contains: [123-456789, (1)23456789]
Added 123-456789 to set.
... now normalized to 123456789
Added (1)23456789 to set.
... now normalized to 123456789
Set contains [(1)23456789, 123-456789].
Unnecessary List contains [123456789, 123456789].
Useful Set contains [123456789].
Related
This feels wrong to me - given a prefix in GCS and knowing my "folders" are consistently named with a long value (e.g. a date in unix time) I want to get the first listing if i was to sort them in descending order. Right now, I only see how to iterate through them all and sort the list:
ListOptions.Builder b = new ListOptions.Builder();
b.setRecursive(false);
b.setPrefix(path);
ListResult result = null;
result = gcsService.list(appIdentity.getDefaultGcsBucketName(), ListOptions.DEFAULT);
List<Long> names = new ArrayList<>();
while (result.hasNext()){
ListItem l = result.next();
String name = l.getName();
logger.info("get top folder" + name);
names.add(Long.valueOf(name));
}
Collections.sort(names);
long topDay = names.get(0);
Maybe a list option i don't see?
If the numbers have the same length, you are looking for the last element on the last page of the results. There is no parameter which reverses result sorting, unfortunately.
If the numbers are not the same length, that's rough. The best way to solve that would probably be to iterate through the options and keep track of the best one you've seen yet, although sorting through them all afterwards also works.
I am trying to get some values from config file. I have lot of keys and want to get only certain values. These values have keys starting with same initial name with a slight variation towards the end.
can Someone help me quickly?
assuming when you say key you mean value (as in values in an array),
final String PREFIX = "yourPrefix";
for(String value : valueList) {
if(value.startwith(PREFIX)) {
<do whatever...>
}
here is the link to the java Doc
http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#startsWith(java.lang.String)
I am assuming you are scanning the config file for Strings that have similar prefixes. Why not try scanning them in grouped instead of scanning them in all in one hashmap. If you know already the specified prefixes try creating an arraylist for each prefix and while scanning receive the given prefix and add it accordingly.
StringTokenizer s = new StringTokenizer ("Configuration File : Server_intenties = keyId_11503, keyId_11903 : Server_passcodes = keyCode_1678, keyCode_9893", " ");
ArrayList<String> keyCode = new ArrayList();
ArrayList<String> keyId = new ArrayList();
while(s.hasMoreTokens){
String key = s.nextToken
if(key.contains("keyId")){
keyId.add(key);
}
if(key.contains("keyCode")){
keyCode.add(key);
}
}
System.out.println(keyCode);
System.out.println(keyId);
I have a HashSet of Strings in the format: something_something_name="value"
Set<String> name= new HashSet<String>();
Farther down in my code I want to check if a String "name" is included in the HashSet. In this little example, if I'm checking to see if "name" is a substring of any of the values in the HashSet, I'd like it to return true.
I know that .contains() won't work since that works using .equals(). Any suggestions on the best way to handle this would be great.
With your existing data structure, the only way is to iterate over all entries checking each one in turn.
If that's not good enough, you'll need a different data structure.
You can build a map (name -> strings) as follows:
Map<String, List<String>> name_2_keys = new HashMap<>();
for (String name : names) {
String[] parts = key.split("_");
List<String> keys = name_2_keys.get(parts[2]);
if (keys == null) {
keys = new ArrayList<>();
}
keys.add(name);
name_2_keys.put(parts[2], keys);
}
Then retrieve all the strings containing the name name:
List<String> keys = name_2_keys.get(name)
You can keep another map where name is the key and something_something_name is the value.
Thus, you would be able to move from name -> something_something_name -> value. If you want a single interface, you can write a wrapper class around these two maps, exposing the functionality you want.
I posted a MapFilter class here a while ago.
You could use it like:
MapFilter<String> something = new MapFilter<String>(yourMap, "something_");
MapFilter<String> something_something = new MapFilter<String>(something, "something_");
You will need to make your container into a Map first.
This would only be worthwhile doing if you look for the substrings many times.
mongodb query is db.test.find({"col1":{"$ne":""}}).count(), I have tried many sources to find the solution, the "col1" must be populated from list array, please help me
I have pasted a part of my code
`
List<String> likey = new ArrayList<String>();
for (DBObject o : out.results())
{
likey.add(o.get("_id").toString());
}
Iterator<String>itkey = likey.iterator();
DBCursor cursor ;
//cursor = table.find();
HashMap<String, String> hashmap = new HashMap<String, String>();
while (itkey.hasNext())
{
System.out.println((String)itkey.next());
String keys = itkey.next().toString();
//System.out.println("keys --> "+keys);
String nullvalue = "";
Boolean listone = table.distinct(keys).contains(nullvalue);
hashmap.put(keys, listone.toString());
//System.out.println("distinct --> "+keys+" "+listone);
//System.out.println("proper str --- >"+ '"'+keys+'"');
}
Iterator<String> keyIterator = hashmap.keySet().iterator();
Iterator<String> valueIterator = hashmap.values().iterator();
while (keyIterator.hasNext()) {
//System.out.println("key: " + keyIterator.next());
while (valueIterator.hasNext()) {
//System.out.println("value: " + valueIterator.next());
//System.out.println("Key: " + keyIterator.next() +""+"value: "+valueIterator.next());
String hashkey = valueIterator.next();
}
}
`
When you post code, it helps if you indent it, so it is more readable. As I mentioned to you on another forum, you need to go back and review the Java collection classes, since you have multiple usage errors in the above code.
Here are a few things you need to do to clean up your code:
1) You don't need to use the itkey iterator. Instead, use:
for (String key : likey)
and get rid of all the itkey.next calls. Your current code only processes every second element of the List. The other ones are printed out.
2) Your HashMap will map a key to a Boolean. Is that what you want? You said you want to count the number of non-zero values for the key. So, the line:
Boolean listone = table.distinct(keys).contains(nullvalue);
is almost certainly in error.
3) When you iterate over the HashMap, you don't need the valueIterator. Instead, get the key (either from the keyIterator, or a variable you define using the simpler iterator syntax above), then use the key to get the matching value using hashmap.get(key).
This will not make your code work, but it will clean it up somewhat - at the moment it is difficult to understand what you are intending it to do.
I'm wanting to compare the strings in an array list taken from my database and join them together..
Here is the code which collects data from my database..
public List<String> getData2List() {
String[] columns = new String[]{ KEY_ROWID, KEY_DATE, KEY_NAME, KEY_PRICE};
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, "1", null, null, null, null);
List<String> results = new ArrayList<String>();
int iCM = c.getColumnIndex(KEY_DATE);
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
results.add(c.getString(iCM));
}
return results;
}
and here is the code to place them in the list..
Database info = new Database(this);
info.open();
List<String> dates = info.getData2List();
lv.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, dates));
info.close();
This all works fine but if there are more than one entry which is the same I end up with a list of the same thing (if this makes sense!?).
Example:
if the list came out like {"01/01/13", "02/01/13", "01/01/13", "03/02/13", "01/01/13"}
I'm trying to make the out come like {"01/01/13", "02/01/13", "03/02/13"}
so that all entry of the same value have been compiled into one.
Any help or ideas is much appreciated.
Just use an Set instead of a List.
An HashSet will provide you unique strings, a List instead can contain same occurrence.
Why don't you just use HashSet<String> ?
Example:
List<String> dates = info.getData2List();
Set<String> uniqueDates = new HashSet<String>(dates);
You can use HashSet instead of ArrayList.
because in your case you will have following advantages
joining two set will be more easier useing addAll method
There is no chance to have duplicate values
You need a Set collection class, basically what "Set" does is, storing only unique values, and if you try to set a new value that already exist in the collection it will just ignore, make sure you are overriding equals, and hashCode method as well in case you are trying to store your own object, look at the documentation for more info about how it works..
http://docs.oracle.com/javase/6/docs/api/java/util/Set.html
Regards!