How to add repeated data in Java array? - java

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

Related

ArrayList - Count if the same Object i listed exact 2 times and if: append to "tempFinalFilterSearchList"

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

How to find index of ArrayList item in String Array

I want to find ArrayList<String> item's index in String Array but every time indexOf() give -1 index .
I cant understand where is wrong? Please check my code and guide me.
public static void arrangeUiComponent() {
ArrayList<String> packageName = new ArrayList<String>();
packageName.add("com.example.dummy");
packageName.add("edu.app.reading");
ArrayList<Integer> index = getIndex(packageName);
}
// searching method
private static ArrayList<Integer> getIndex(ArrayList<String> searchName) {
ArrayList<Integer> indexList = new ArrayList<Integer>();
String[] collectionData = new String[] { "com.example.app",
"com.example.appdemo", "com.example.dummy", "edu.app.reading",
"edu.app.knowledge" };
/*
* for iterating each and every item of list
*/
for (int i = 0; i < searchName.size(); i++) {
Log.i("MISSION", "value will be: " + searchName.get(i).toString());
/*
* for searching listItem in package name array
*/
for (int j = 0; j < collectionData.length; j++) {
indexList.add(collectionData.toString().indexOf(searchName.get(i).toString()));
break;
}
}
return indexList;
}
Replace
for (int j = 0; j < collectionData.length; j++) {
indexList.add(collectionData.toString().indexOf(searchName.get(i).toString()));
break;
}
with
indexList.add(Arrays.asList(collectionData).indexOf(searchName.get(i)));
Here is the working demo of your code. Arrays.asList converts your string array to a list. Why don't you use a list instead of string collectionData array?
Use a debugger and look the value of collectionData.toString().
It returns something that is not your list of strings. That the object representation.
Quote from javadoc:
The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `#', and the unsigned hexadecimal representation of the hash code of the object.
EDIT:
whoops, collectionDatais an array, not a List, you should use
java.util.Arrays.asList(collectionData).indexOf(searchName.get(i))
It will search for the searchName.get(i)string inside the collectionDataList and not inside the collectionData representation which is a String (that's why indexOf is valid).
As searchName is a list of String, you don't need to add the toString() on searchName.get(i)
I'm assuming that in the indexLIst you want corresponding packageName's index values.
I don't think this will work in the way you want it.
The indexList being an Arraylist(data is not stored in the input order) might not have corresponding index values.
Ex:
packageName list:
"com.example.dummy", "edu.app.reading"
so the indexList should have values:
2 , 3
but it might contain:
3, 2 as well because data is not stored in the order in which it is entered.
You should probably use a linkedList if you want to preserve the order.
use a Hashmap<String, integer>.
You can do something like this using a hashmap:
public static void arrangeUiComponent() {
ArrayList<String> packageName = new ArrayList<String>();
packageName.add("com.example.dummy");
packageName.add("edu.app.reading");
HashMap<String, Integer> indexMap = getIndex(packageName);
for (String s : packageName) {
int index = indexMap.get(s);
}
}
private static HashMap<String, Integer> getIndex(ArrayList<String> searchName) {
HashMap<String, Integer> indexMap = new HashMap<String, Integer>();
String[] collectionData = new String[] { "com.example.app", "com.example.appdemo", "com.example.dummy",
"edu.app.reading", "edu.app.knowledge" };
for (String search : searchName) {
for (int i = 0; i < collectionData.length; i++) {
if (search.equals(collectionData[i])) {
indexMap.put(search, i);
break;
}
}
}
return indexMap;
}
You use collectionData.toString() which return [Ljava.lang.String;#15db9742. So collectionData.toString().indexof() always find nothing and return -1
To solve this you can use:
Declare arraylist as
ArrayList<String>cd = new ArrayList<String>(Arrays.asList(collectionData));
which convert String[] to ArrayList then ArrayList gives us facility of finding element with indexof().
Then in your inner for loop
for (int j = 0; j < collectionData.length; j++) {
indexList.add(cd.indexOf(searchName.get(i).toString()));
break;
}
toString() method of an array returns something similar to [Ljava.lang.String;#2a139a55. This is the reason you were getting index value as -1.
Other than the solution sam2090 provided, you can try 2 more options.
Replace
indexList.add(collectionData.toString().indexOf(searchName.get(i).toString()))
with
indexList.add(java.util.Arrays.binarySearch(collectionData, searchName.get(i)))
or
Replace collectionData.toString() with java.util.Arrays.toString(values)

Comparing Elements in the same ArrayLists and add to Hashmap

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

issue with sort data

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 !! :)

Adding values in to a HashMap

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
}

Categories

Resources