i am developing an app in which i get data from server and display in map. but before display it on map's balloon i have just sort data by one field name is "Destination" and there are method made na,e is ..GOTOSORT....
now problem is i got variables s with length 1 and there for the for loop are run only 1 time , but there are 42 data are come from webservices so please check it and tell me what is the problem
private void GOTOSORT() {
Log.i(TAG, " SORT ");
Map<Float, Integer> map = new TreeMap<Float, Integer>();
for (int i = 0; i < lng_timeStamp.length; ++i) {
map.put((float) lng_timeStamp[i], i);
}
Collection<Integer> indices = map.values();
System.out.println("indices" + indices);
Integer s[] = (Integer[]) indices.toArray(new Integer[0]);
Log.i(TAG, "s.length"+s.length);
for (int i = 0, n = s.length; i < n; i++) {
System.out.println(s[i]);
int_sort_MyhourGetTime[i] = int_MyhourGetTime[s[i]];
int_sort_MyMinGetTime[i] = int_MyMinGetTime[s[i]];
lng_sor_timeStamp[i] = lng_timeStamp[s[i]];
arr_sort_ServiceNumber[i] = arr_ServiceNumber[s[i]];
arr_sort_Destination[i] = arr_Destination[s[i]];
}
If you want to sort your list , you should follow the Java's comparatorFollow here
It will return you a sorted list in any order.
All the best !! :)
Related
Basicly im trying to look through an Arraylist to check if the same object is listed 2 times - and if: append to "tempFinalFilterSearchList"
Im not allowed to use Hashmap (School assignment).
UPDATE - This code actual works now... Now I just need to remove dublicates from "tempFinalFilterSearchList"
public List<Venue> filterToFinalSearchList()
{
for (int i=0; i < tempFilterSearchList.size(); i++)
{
int occurences=0;
for (int j = 0; j < tempFilterSearchList.size(); j++)
{
if (tempFilterSearchList.get(i).getVenueId() == tempFilterSearchList.get(j).getVenueId())
{
occurences++;
}
}
if (occurences == 2)
{
tempFinalFilterSearchList.add(tempFilterSearchList.get(i));
}
}
return tempFinalFilterSearchList;
}
if the same venueId is listed exact 2 times in "tempfilterSearchList", then the Object have to be added to "tempFinalFilterSearchList"...
have tried several different things now, without luck - And also search here / google - there alot of solutions, but all with Hashmap which im not allowed to use.
Thank you in advance for any advise.
First of all keep in mind that using the remove function inside a loop for the same list is not safe(Unless using an iterator).
I assume you have a class let's call it A that has the attribute venueId.
It looks something like this + other attributes that you want:
public class A {
private int venueId;
public A(int venueId) {
this.venueId = venueId;
}
public int getVenueId() {
return venueId;
}
public void setVenueId(int venueId) {
this.venueId = venueId;
}
}
1.Create a function that parses the list and counts the number of times an object with the same venueId repeats itself
public boolean doesVenueIdRepeatInList(int venueId, List<A> list) {
int timesRepeated = 0;
//Parse the list and count the number of items that have the same venueId
for (int i = 0; i < list.size(); i++) {
if (list.get(i).getVenueId() == venueId) {
timesRepeated++;
}
}
//If the venueId repeats more than 3 times
if (timesRepeated >= 3) {
return true;
}
return false;
}
3.Now to the code that actually does what you asked.
We will parse the list and identify the the objects that repeat more than 3 times.
If they repeat more than 3 times we won't add them to the new list
List<A> tempFilterSearchList = Arrays.asList(
new A(1),
new A(2),
new A(1),
new A(2),
new A(3),
new A(1),
new A(2)
);
//We will be using a new list to put the result in
//It's not safe to use the delete function inside a loop
List<A> filteredList = new ArrayList<>();
//Count the number an object repeats and if it repeats more than 3 times store it inside repeatedVenueIds
for (int i=0; i < tempFilterSearchList.size(); i++)
{
int venueId = tempFilterSearchList.get(i).getVenueId();
boolean itRepeat3Times = doesVenueIdRepeatInList(venueId, tempFilterSearchList);
//If it doesn't repeat more than 3 times add it to the new list
if(!itRepeat3Times) {
filteredList.add(tempFilterSearchList.get(i));
}
}
You have your result inside filteredList
It is a better advanced option to use 'iterator' since it allows you to remove elements while iterating an arraylist
ArrayList<Integer> tempFilterSearchList = new ArrayList<Integer>(Arrays.asList(1,2,5,3,7,3,7,3) );
Iterator itr = tempFilterSearchList.iterator();
while (itr.hasNext())
{
int count = 0;
int number = (Integer)itr.next();
for (int i=0; i < tempFilterSearchList.size(); i++)
{
int x = tempFilterSearchList.get(i);
if (x == number)
{
count++;
}
}
if( count != 3 )
{
itr.remove();
}
}
"using the remove function inside a loop for the same list is not safe. " this will not be an issue if you use iterator in java which is a advance option in java language
Your code must look like the folowing. First of all you should loop over all the elements in tempFilterSearchList. Then for each element, you should count the number of times it appears in the list. I choosed rather to place all the positions where the current elements' venueId occures in separate List to further delete them easly.
ArrayList<Integer> occurrences = new ArrayList<Integer>()
for (int i=0; i < tempFilterSearchList.size(); i++)
for (int j=0; j < tempFilterSearchList.size(); j++){
if(tempFilterSearchList.get(i).getVenueId() ==tempFilterSearchList.get(j).getVenueId()){
occurrences.add(j)
}
}
if(occurrences.size() != 3){
for(int j:occurrences){
tempFilterSearchList.remove(occurrences[j])
}
}
}
I am having an array with name (String name[]={"a","b","a","c","a","b","c"};) and another array with quantity (int qty[]={10,20,10,40,10,40,70};) corresponding with name array. Now, i just want another array having addition of similar qty[] values corresponding to their name[] i.e. i need tempname[]={"a","b","c"} and tempqty[]={30,60,110}. here tempname contains unique values from name and tempqty contains addition of a,b,c.
temp=name;
qty1=qty;
for(i=0;i<name.length;i++){
temp1=qty[i];
for(int j=0;j<name.length;j++){
if (name[i]==temp[j+1]){
temp1=temp1+qty1[j+1];
}
}
}
I tried above method. Here, i am able to get addition of qty of "a" name but i am not getting my result. please suggest me on this or give me any another way to solve the problem. thank you in advance.
You can do this easily by ArrayList. I did this for you:
String name[]={"a","b","a","c","a","b","c"};
int qty[]={10,20,10,40,10,40,70};
ArrayList<String>tempname= new ArrayList<String>();
ArrayList<Integer>tempqty= new ArrayList<Integer>();
for(int i=0;i<name.length;i++){
int index=tempname.indexOf(name[i]);
if(index==-1){
tempname.add(name[i]);
tempqty.add(qty[i]);
}
else{
tempqty.set(index,tempqty.get(index)+qty[i]);
}
}
for(int i=0;i<tempname.size();i++){
System.out.printf(tempname.get(i)+" ");
}
System.out.println();
for(int i=0;i<tempqty.size();i++){
System.out.printf(tempqty.get(i)+" ");
}
Use a HashMap:
HashMap<String, Integer> quantity = new HashMap<>();
for(int i = 0; i < name.length; i++) {
if(!quantity.containsKey(name[i])) {
quantity.put(name[i], qty[i]);
} else {
quantity.put(name[i], quantity.get(name[i]) + qty[i]);
}
}
Untested, but you'll get the idea.
I suggest to use something like hashmaps for this
Example:
HashMap<String, int> hmap = new HashMap<String, int>();
hmap.put("a", 1);
hmap.put("b", 2);
To get a value use
hmap.get("a"); // will give 1
To loop through everything
Iterator it= hmap.keySet().iterator();
while(it.hasNext()) {
String key=(String)it.next();
int value=(int)hmap.get(key);
// do something
}
If you want to put values together because they belong together you could create a class.
class MyStoreThing {
String name;
int quantity;
}
int getSummarizedQuantityOfAllWithName(String name) {
int summarizedQuantity = 0;
for (int i = 0; i < myList.length; i++) {
summarizedQuantity += name.equals(myList.getName()) ? myList.getQuantity : 0;
}
return summarizedQuantity;
}
ArrayList<MyStoreThing> myList = new...;
// populate list: myList.add(new MyStoreThing("a", 10)) ...
// call getSummarizedQuantityOfAllWithName("a");
I got a quick question.
Currently, I have a userList (of String) and timeLime (of Integer).
These values were added in order and therefore each .get(i) will contain the user (userList) with his time (timeList).
As there may be duplicate instances of users in the name ArrayList, I would like to sum up the total time for each user in timeList and put it to a hashmap of <String, Integer>, but I do not know how to do it.
Currently, what I have done is:
for (int i = 0; i < userList.size(); i++) {
count = 0;
for (int j = 0; j <userList.size(); j++) {
if (!userList.get(i).equals(userList.get(j))) {
count++;
}
}
if (count == userList.size() -1) {
System.out.println("Adding in " + userList.get(i));
map.put(userList.get(i), timeList.get(i));
}
}
I am stuck till the point where if there is a match. I do not know how to add the time together and put it in the hashmap.
I'm not very proficient in Java and would like some help. Thanks in advance.
Do you want to create one HashMap with user and the sum of time that may appear anywhere in the two lists? If that is the case, the following code will do it for you.
List<String> userList = new ArrayList<String>(Arrays.asList("ann", "john", "tim", "ann"));
List<Integer> timeList = new ArrayList<Integer>(Arrays.asList(1, 2, 3, 5));
Map<String, Integer> userTimeMap = new HashMap<String, Integer>();
for (int i = 0; i < userList.size(); i++) {
String user = userList.get(i);
Integer time = userTimeMap.get(user);
if (time == null) {
userTimeMap.put(user, timeList.get(i));
} else {
userTimeMap.put(user, time + timeList.get(i));
}
}
Result : {john=2, ann=6, tim=3}
I would do it in this way:
for (int i = 0; i < userList.size(); i++) {
// check whether the entry is already there
if (map.containsKey(userList.get(i))){
// If already exists add
map.put(userList.get(i), map.get(userList) + timeList.get(i));
}else{
// else make a new entry
map.put(userList.get(i), timeList.get(i));
}
}
I'm writing a method that allows me to count how many times an element of type String shows up in a LinkedList of type Strings. my code shown below does not work. I keep getting index out of bounds in the line i commented on down below. Can't seem to find the bug
public int findDuplicate (LinkedList<String> e) {
int j = 1;
LinkedList<String> test = e;
while (!test.isEmpty()){
test = e;
String value = test.pop();
//Screws up here when i = 6
for(int i =0; i<=test.size() && test.get(i)!=null; i++){
String value3 = test.get(i);
if(e.get(i).equals(value) && i<=test.size()){
String value2 = test.get(i);
j++;
String Duplicate = e.get(i);
e.remove(i);
}
}
System.out.println(value + " is listed " + j + " times");
}
return j;
}
using hashmaps.. still doesn't work
public void findDuplicate (LinkedList e) {
Map<String,Integer> counts = new HashMap<String,Integer>();
while(!e.isEmpty()){
String value = e.pop();
for(int i =0; i<e.size(); i++){
counts.put(value, i);
}
}
System.out.println(counts.toString());
}
My code should go through the linked list find out how many times an element within the list appears and deletes duplicates from the list at the same time. Then prints the element and the number of times it appears in the list. I posted about this last night but didn't get a response yet. Sorry for the repost.
You are running off the end of the list. Change
for(int i =0; i<=test.size() && test.get(i)!=null; i++){
to
for(int i =0; i< test.size() && test.get(i)!=null; i++){
Valid indexes for a List (or an array) are 0 through size() - 1.
Regarding your hashmap example to count the duplicates:
#Test
public void countOccurrences() {
LinkedList<String> strings = new LinkedList<String>(){{
add("Fred");
add("Fred");
add("Joe");
add("Mary");
add("Mary");
add("Mary");
}};
Map<String,Integer> count = count(strings,new HashMap<String,Integer>());
System.out.println("count = " + count);
}
private Map<String, Integer> count(List<String> strings, Map<String, Integer> runningCount) {
if(strings.isEmpty()) {
return runningCount;
}
String current = strings.get(0);
int startingSize = strings.size();
while(strings.contains(current)) {
strings.remove(current);
}
runningCount.put(current, startingSize - strings.size());
return count(strings,runningCount);
}
If you want the original strings list preserved you could do
Map<String,Integer> count = count(new LinkedList<String>(strings),new HashMap<String,Integer>());
System.out.println("strings = " + strings);
System.out.println("count = " + count);
Check out google's guava collections which has a perfect class for maintaining a map and getting a count:
https://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained#BiMap
Multiset<String> wordsMultiset = HashMultiset.create();
wordsMultiset.addAll(words);
// now we can use wordsMultiset.count(String) to find the count of a word
I hope you realize what the test = e statement is doing. After this statement executes both test and e refer to the same object.
If anyone of them modifies the list, the other sees it as they both are looking at the same object.
If this is not intended you need to clone the list before assigning it to another list reference.
This doesn't affect your out of bounds issue, but you are removing elements from your list while still evaluating it. If you remove an element, you should call i-- afterwards, or you skip the next entity (which is re-indexed) for evaluation.
Also of note regarding your code, I see you are trying to make a copy of your list, but standard assignment means test and e both point to the same instance. You need to use Collections.copy() see this SO thread on how to use the class.
I need help to add the values from a String array into a HashMap.
if (!loaded){
synchronized(syncLock){
if (!loaded){
loaded=true;
if (prefix!=null){
prefixMap = new HashMap<Integer, Float>();
String userDefaultPrefix[] = prefix.split("~");
}
}
}
}
I have the strings stored in userDefaultPrefix, and i need to add those values into prefixMap. TIA
If I get you right and you're sure in data quality than you can fill prefixMap following way:
for (int i = 0; i < userDefaultPrefix.length; i += 2) {
if (i+1 < userDefaultPrefix.length) {
prefixMap.put(Integer.parseInt(userDefaultPrefix[i]),
Float.parseFloat(userDefaultPrefix[i+1]));
}
}
assuming you want a map of (i->userDefaultPrefix[i]):
for (int i = 0; i < userDefaultPrefix.length;i++) {
prefixMap.put(i,userDefaultPrefix[i]); //note that the autoboxing automatically boxes your int to an Integer
}