Sorting in a hashMap - java

I'm having some trouble sorting out this code, which is in a hashmap - I also need some help sorting out a similar code set for a double (price). Thank You.
#SuppressWarnings("unused")
public class Inventory {
Scanner in = new Scanner(System.in);
ArrayList<Sellable> groceries;
HashMap<String, Integer> stock;
public Inventory() {
groceries = new ArrayList<Sellable>();
stock = new HashMap<String, Integer>();
//HARDCODING...:
Sellable n1 = new Produce("Corn", 3, 5.00);
Sellable n2 = new Snack("Natural Popcorn Seeds", 2.50);
Sellable n3 = new Produce("Potatoes", 3, 5.00);
Sellable n4 = new Snack("Organic Potato Chips", 2.50);
Sellable n5 = new Produce("Apples", 5, 1.75);
Sellable n6 = new Snack("Apple Juice - 128 oz.", 3.50);
Sellable n7 = new Produce("Oranges", 5, 1.75);
Sellable n8 = new Snack("Orange Juice - 128 oz.", 3.50);
//ADD TO HASHMAP
groceries.add(n1);
groceries.add(n2);
groceries.add(n3);
groceries.add(n4);
groceries.add(n5);
groceries.add(n6);
groceries.add(n7);
groceries.add(n8);
//PUT UP FOR PRINTING
stock.put(n1.getName(), 50);
stock.put(n2.getName(), 100);
stock.put(n3.getName(), 50);
stock.put(n4.getName(), 100);
stock.put(n5.getName(), 50);
stock.put(n6.getName(), 100);
stock.put(n7.getName(), 50);
stock.put(n8.getName(), 100);
}
//Sorting Method 1
#SuppressWarnings("unchecked")
public void sortByName() {
groceries = new ArrayList<Sellable>();
stock = new HashMap<String, Integer>();
{
if (stock != null) {
List<Sellable> groceries = new ArrayList<Sellable>();
stock.addAll(((Entry<String, Integer>) stock).getValue(), groceries);
Collections.sort(groceries, new Comparator<Sellable>() {
public int compare(Sellable product1, Sellable product2) {
try {
Sellable choice1 = (Sellable) product1;
Sellable choice2 = (Sellable) product2;
//LESS THAN
if (choice1.getName().compareTo(choice2.getName()) < 0) {
return -1;
} //GREATER THAN
else if (choice1.getName().compareTo(choice2.getName()) > 0) {
return 1;
} //EQUALS
else {
return 0;
}
} catch (ClassCastException FAIL) {
return -2;
}
}
});
}
}
}
}

Please remove the lines of code,
groceries = new ArrayList<Sellable>();
stock = new HashMap<String, Integer>();
from your mehod sortByName().
This lines reset the groceries and stock to empty.

Sorry, but neither your code or your Question makes a lot of sense to me.
Your sortByName is clobbering both groceries and stock.
Then it is apparently attempting to copy from the (now) empty HashMap to the ArrayList. But it is nonsensical because
you are attempting to use a non-existent method (HashMap.addAll),
you are casting a HashMap to an Entry,
and so on.
The Comparator looks plausible for sorting "by name", but your code that returns -2 in the event of a ClassCastException is wrong. You should just let the exception propagate ... if it arises. You don't actually do a type-cast in the Comparator. The arguments have the correct type. (Casting a Sellable to a Sellable? Why ???)

Thought of adding a new answer instead of editing my previous answer.
Please note that you should not (re)initialize the member variables in methods unless it is really required. Also I have used String.compareTo() to compare names.
Please find below the modified sort method:
#SuppressWarnings("unchecked")
public void sortByName() {
// groceries = new ArrayList<Sellable>();
// stock = new HashMap<String, Integer>();
if (stock != null) {
//List<Sellable> groceries = new ArrayList<Sellable>();
//stock.addAll(((Entry<String, Integer>) stock).getValue(), groceries);
Collections.sort(groceries, new Comparator<Sellable>() {
public int compare(Sellable product1, Sellable product2) {
try {
return product1.getName().compareTo(product2.getName());
} catch (Exception FAIL) {
return -2;
}
}
});
}
}
}

Related

JAVA - BFS to a limited friendship level in a graph

I am working on an undirected graph implementation for a simple social network. Users are represented using their IDs (Integers), and I need to find different levels of friendship.
I used the Adjacency List approach as my graph is very sparse. I used a hashmap to hold users and their friends:
Map<Integer, Set<Integer>> graph;
Using this implementation, I am able to find the first and second levels of friendship. However, I wrote a method that uses BFS to find if two users are fourth-level friends.
For example, if the graph contains following edges:
1-2
2-3
3-4
4-5
Then 1 and 5 are fourth-level friends, and my method should return true when 1 and 5 are passed to it as parameters.
The problem is that my method always returns false when it is called in the main, even if the method itself is tested and is correct! Here is the method, and again it is correct and working.
public boolean checkLevelBFS(Integer source, Integer dest) {
Queue<Integer> toVisitQueue = new LinkedList<>(graph.get(source));
Set<Integer> visited = new HashSet<>();
visited.add(source);
Integer inreaser = new Integer(-1); // indicator for level increase
toVisitQueue.add(inreaser);
int level = 1; // because we already passed the source and started from its children nodes
while (level <= 4 && !toVisitQueue.isEmpty()) {
Integer currentNode = toVisitQueue.remove();
if (currentNode.equals(dest)) {
return true;
}
if (visited.contains(currentNode)) {
continue;
}
if (currentNode.equals(inreaser)) {
level++;
toVisitQueue.add(inreaser);
continue;
}
visited.add(currentNode);
for (Integer child : graph.get(currentNode)) {
if (!visited.contains(child)){
toVisitQueue.add(child);
}
}
}
return false;
}
The part that makes the code return false is below:
public static void main(String[] args) {
Basics x = new Basics();
x.graph = new HashMap<>();
Set<Integer> s = new HashSet<>();
s.add(2);
x.graph.put(1, s);
s = new HashSet<>();
s.add(1);
s.add(3);
x.graph.put(2, s);
s = new HashSet<>();
s.add(2);
s.add(4);
x.graph.put(3, s);
s = new HashSet<>();
s.add(3);
s.add(5);
x.graph.put(4, s);
s = new HashSet<>();
s.add(4);
s.add(6);
x.graph.put(5, s);
s = new HashSet<>();
s.add(5);
x.graph.put(6, s);
if (!x.initialCheck(1, 5)) {
System.out.println("A new user is involved");
} else {
if (x.levelOneFriends(1, 5)) {
System.out.println("friends");
} else {
System.out.println("not friends");
if (x.levelTwoFriends(1, 5)) {
System.out.println("friends level 2");
} else {
System.out.println("not friends of level 2");
if (x.checkLevelBFS(1, 5)) {
System.out.println("YES - friends of level 4");
} else {
System.out.println("NO - not friends of level 4");
}
}
}
}
System.out.println(x.checkLevelBFS(1, 2));
System.out.println(x.checkLevelBFS(1, 3));
System.out.println(x.checkLevelBFS(1, 4));
System.out.println(x.checkLevelBFS(1, 5));
System.out.println(x.checkLevelBFS(1, 6));
}
Output:
not friends
not friends of level 2
NO - not friends of level 4
false
false
false
false
false
The first two lines are correct outputs, the third is not correct as 1 and 5 are frieds of level 4, and should print YES -
The following 'false' outputs are weird too!
'initialCheck' checks if any of the two users is not already in the graph.
'levelOneFriends' checks if the two objects are direct friends.
'levelTwoFriends' checks if the two objects are in the relation Friend of Friend.
Any help?
Thanks!
[Edited after OP's comment showing levelTwoFriends]
public boolean levelTwoFriends(Integer user1, Integer user2) {
Collection<Integer> c = graph.get(user1);
// c.retainAll(graph.get(user2));
// return !c.isEmpty();
// true only if a non-void intersection
return false==Collections.disjoint(c, graph.get(user2));
}
or, as a one-liner
public boolean levelTwoFriends(Integer user1, Integer user2) {
return false==Collections.disjoint( graph.get(user1), graph.get(user2) );
}
[Edited after update with x.initialCheck]
Your bug then must be in the x.initialCheck and the other stuff that you are doing before actually getting into x.checkLevelBFS. Verify the x.initialCheck and x.levelOneFriends against modification in the internal representation of you adjacency list (there must be one there - run the in debugger and keep an eye on modification of the content). Why I say this? Because the below code works as intended:
static public void main(String[] args) {
ExampleTest x=new ExampleTest(); // in your case, it's Basics
x.graph=new HashMap<>();
x.graph.put(1, new HashSet<>(Arrays.asList(2)));
x.graph.put(2, new HashSet<>(Arrays.asList(1,3)));
x.graph.put(3, new HashSet<>(Arrays.asList(2,4)));
x.graph.put(4, new HashSet<>(Arrays.asList(3,5)));
x.graph.put(5, new HashSet<>(Arrays.asList(4,6)));
x.graph.put(6, new HashSet<>(Arrays.asList(5)));
System.out.println(x.checkLevelBFS(1, 2)); // true
System.out.println(x.checkLevelBFS(1, 3)); // true
System.out.println(x.checkLevelBFS(1, 4)); // true
System.out.println(x.checkLevelBFS(1, 5)); // true
System.out.println(x.checkLevelBFS(1, 6)); // false
}
"The problem is that my method always returns false!"
But it doesn't! Your bug may be in some other place!!!
I'll be marking this as Works for me and closing the bug.
My code used for driving the tests.
class ExampleTest {
Map<Integer, Set<Integer>> graph;
static public void main(String[] args) {
ExampleTest x=new ExampleTest();
x.graph=new HashMap<>();
x.graph.put(1, new HashSet<>(Arrays.asList(2)));
x.graph.put(2, new HashSet<>(Arrays.asList(3)));
x.graph.put(3, new HashSet<>(Arrays.asList(4)));
x.graph.put(4, new HashSet<>(Arrays.asList(5)));
x.graph.put(5, new HashSet<>(Arrays.asList(6)));
System.out.println(x.checkLevelBFS(1, 2)); // true
System.out.println(x.checkLevelBFS(1, 3)); // true
System.out.println(x.checkLevelBFS(1, 4)); // true
System.out.println(x.checkLevelBFS(1, 5)); // true
System.out.println(x.checkLevelBFS(1, 6)); // false
}
// verbatim copy of your method here
public boolean checkLevelBFS(Integer source, Integer dest) {
Queue<Integer> toVisitQueue = new LinkedList<>(graph.get(source));
Set<Integer> visited = new HashSet<>();
visited.add(source);
Integer inreaser = new Integer(-1); // indicator for level increase
toVisitQueue.add(inreaser);
int level = 1; // because we already passed the source and started from its children nodes
while (level <= 4 && !toVisitQueue.isEmpty()) {
Integer currentNode = toVisitQueue.remove();
if (currentNode.equals(dest)) {
return true;
}
if (visited.contains(currentNode)) {
continue;
}
if (currentNode.equals(inreaser)) {
level++;
toVisitQueue.add(inreaser);
continue;
}
visited.add(currentNode);
for (Integer child : graph.get(currentNode)) {
if (!visited.contains(child)){
toVisitQueue.add(child);
}
}
}
return false;
}
}

Java Array Sorting based on multiple parameters

I have an array that I want to sort in ascending order. However, I want to sort them with reference to a boolean array.I would like to sort the values that are true in ascending order, followed by the values that are false in ascending order.
Little stuck on how to get there.
This is what I have currently:
Object[] arr = new Object[6];
arr[0] = new Object(2);
arr[1] = new Object(5);
arr[2] = new Object(3);
arr[3] = new Object(1);
arr[4] = new Object(6);
arr[5] = new Object(4);
Available[] avalarr = new Available[6];
availarr[0] = new Available (true);
availarr[1] = new Available (false);
availarr[2] = new Available (false);
availarr[3] = new Available (true);
availarr[4] = new Available (true);
availarr[5] = new Available (false);
I need the output to be:
1 2 6 3 4 5
Code:
import java.util.Arrays;
public class SelectiveSort {
public static void main(String[] args) {
Item [] items = new Item [6];
items[0] = new Item(2, true);
items[1] = new Item(5, false);
items[2] = new Item(3, false);
items[3] = new Item(1, true);
items[4] = new Item(6, true);
items[5] = new Item(4, false);
System.out.println("Before Sorting:");
// Removed enhanced for loop
for(int i = 0; i < items.length; i++) {
System.out.print(items[i].getIntValue() + " ");
}
// Sorting
Arrays.sort(items);
System.out.println("\n\nAfter Sorting:");
// Removed enhanced for loop
for(int i = 0; i < items.length; i++) {
System.out.print(items[i].getIntValue() + " ");
}
System.out.println();
}
}
class Item implements Comparable<Item> {
private int _intValue;
private boolean _boolValue;
public Item(int intValue, boolean boolValue) {
_intValue = intValue;
_boolValue = boolValue;
}
public int getIntValue() { return _intValue; }
public boolean getBoolValue() { return _boolValue; }
#Override
public int compareTo(Item otherItem) {
// Using explicit comparison
int boolComparison = (_boolValue == otherItem._boolValue) ? 0 :
(_boolValue) ? 1 : -1;
return (boolComparison != 0) ? -boolComparison :
( (_intValue == otherItem.getIntValue()) ? 0 :
(_intValue > otherItem.getIntValue()) ? 1 : -1);
}
}
Output:
Before Sorting:
2 5 3 1 6 4
After Sorting:
1 2 6 3 4 5
Explanation:
The idea is to let your "Item" implement Comparable, and override the compareTo(Item otherItem) function based on the desired order.
Once that is done, all you need to do is to call Arrays.sort() on your array of Item.
Version 2 (w/o Comparable/Comparator):
public class SelectiveSort {
public static void main(String[] args) {
Item [] items = new Item [6];
items[0] = new Item(2, true);
items[1] = new Item(5, false);
items[2] = new Item(3, false);
items[3] = new Item(1, true);
items[4] = new Item(6, true);
items[5] = new Item(4, false);
System.out.println("Before Sorting:");
for(int i = 0; i < items.length; i++) {
System.out.print(items[i].getIntValue() + " ");
}
// Sorting
bubbleSort(items);
System.out.println("\n\nAfter Sorting:");
for(int i = 0; i < items.length; i++) {
System.out.print(items[i].getIntValue() + " ");
}
System.out.println();
}
public static void bubbleSort(Item [] items) {
int n = items.length;
do {
int newN = 0;
for(int i = 1; i < n; i++) {
if(compareTo(items[i-1], items[i]) == 1) {
Item temp = items[i-1];
items[i-1] = items[i];
items[i] = temp;
newN = i;
}
}
n = newN;
} while (n != 0);
}
public static int compareTo(Item item1, Item item2) {
int boolComparison = (item1.getBoolValue() == item2.getBoolValue())
? 0 : (item1.getBoolValue()) ? 1 : -1;
return (boolComparison != 0) ? -boolComparison :
( (item1.getIntValue() == item2.getIntValue()) ? 0 :
(item1.getIntValue() > item2.getIntValue()) ? 1 : -1);
}
}
(To expand on my comment:
You need a basic "thing":
class Thing {
boolean newAvailable;
int order;
public Thing(boolean newAvailable, int order) {
...
}
}
...and a Comparable...
class CompareThings implements Comparator<Thing> {
...
int compare(Thing t1, Thing t2) {
if (t1.newAvailable!=t2.newAvailable)
return t1.newAvailable==true ? 1 : -1;
return t1.order-t2.order;
}
}
(Note that t1.newAvailable==true is redundant, but I think it clarifies what's going on here.)
Now build an array of Thing and call Arrays.sort(Thing[] things, CompareThings);

Null pointer exception, taking data form lists and arrays

I've checked everything several time, can't get where I am wrong..
Main class:
try
{
File productData = new File("productData.txt");
Product [] consideredRange = InputFileData
.readProductDataFile(productData);
ElectronicsEquipmentSupplier management =
new ElectronicsEquipmentSupplier(1, 12, consideredRange);
File customerData = new File("CustomerData.txt");
Scanner fileScan = new Scanner(customerData);
while(fileScan.hasNext())
management.addNewCustomer(InputFileData.
readCustomerData(fileScan));
management.addNewPurchaseOrder("21/01/12", "PSC-1235", "kD/9767", 50);
}
catch(Exception e)
{
System.out.println(e);
e.printStackTrace();
}
InputFileData class works perfectly. I have created an object of ElectronicsEquipmentSupplier with a consideredRange of products. Also added customers to a customersList.
Here is ElectronicsEquipmentSupplier class:
public class ElectronicsEquipmentSupplier
{
private int currentMonth;
private int currentYear;
private Product [] productRange;
private CustomerDetailsList customersList;
private PurchaseOrderList currentYearList;
private PurchaseOrderList lastYearList;
public ElectronicsEquipmentSupplier(int currentMonth, int currentYear, Product [] range)
{
this.currentMonth = currentMonth;
this.currentYear = currentYear;
productRange = new Product[range.length];
customersList = new CustomerDetailsList();
currentYearList = new PurchaseOrderList();
lastYearList = new PurchaseOrderList();
}
public void addNewPurchaseOrder(String dateStr, String customerID,
String productCode, int qty) throws IncorrectPurchaseOrderException
{
// check for positive order quantity
if(qty < 1)
throw new IncorrectPurchaseOrderException("Order quantity must be"
+ " positive!");
// check for the product code in given range and get that product
Product foundProduct = null;
for(int i = 0; i < productRange.length; i++)
{
if(productRange[i].getProductCode().equals(productCode))
{
foundProduct = productRange[i];
break;
}
}
if(foundProduct == null)
throw new IncorrectPurchaseOrderException("Product code is not in"
+ " the product range!");
try
{
// creating OrderDate object and getting appropriate discount
OrderDate newDate = new OrderDate(dateStr);
int discount = customersList.findCustomer(customerID).
getDiscountRate();
// creating purchase order and adding it to a list
PurchaseOrder givenOrder = new PurchaseOrder(newDate, customerID,
foundProduct, qty, discount);
currentYearList.addPurchaseOrder(givenOrder);
// updating the record of purchasing customer
int priceValue = givenOrder.getFullPriceValue();
customersList.findCustomer(customerID)
.updateTotalOrdersValue(priceValue);
}
catch(Exception e)
{
throw new IncorrectPurchaseOrderException("The problem is with: "
+ "\n" + e);
}
}
It shows that I've got NullPointerException at: if(productRange[i].getProductCode().equals(productCode))
and in the main class at:
management.addNewPurchaseOrder("21/01/12", "PSC-1235", "kD/9767", 50);
Can't get why, as I have all required info..
Thank you!
Update 1:
Added this to the main method to solve first issue:
for(int i = 0; i < consideredRange.length; i++)
management.getProductRange()[i] = consideredRange[i];
But now the ID of a customer cannot be found...
That's the method in CustomerDetailsList class, which throws exception:
public CustomerDetails findCustomer(String givenID)
throws CustomerNotFoundException
{
int i = 0;
boolean match = false;
while(!match && i < listOfCustomerDetails.size())
{
match = listOfCustomerDetails.get(i).getCustomerID()
.equals(givenID);
i++;
}
if(!match)
throw new CustomerNotFoundException("The provided ID has not been"
+ " found");
else
return listOfCustomerDetails.get(i);
}
Update 2: updated .findCustomer() as SMA suggested
You are trying to initialize product in constructor like
productRange = new Product[range.length];
And then using it like:
if(productRange[i].getProductCode().equals(productCode))
Now you allocated space for your array but individual array elements i.e. products are not initialized and hence you get NullPointerException. To resolve the issue, you could do something like:
productRange[i] = new Product(..);//and then use it
Most likely because productRange[i] has not been initialized.
In your constructor you need to fully initialise the productRange array. Right now you are just creating an array of null references.
public ElectronicsEquipmentSupplier(int currentMonth,
int currentYear,
Product [] range) {
this.currentMonth = currentMonth;
this.currentYear = currentYear;
productRange = new Product[range.length];
for (int i = 0; i < productRange.length; i++) {
productRange[i] = range[i];
}
customersList = new CustomerDetailsList();
currentYearList = new PurchaseOrderList();
lastYearList = new PurchaseOrderList();
}
The above solution build a new array which reference the same objects as the range array passed to the constructor.
You may just want to reference the array without any allocation, e.g.
public ElectronicsEquipmentSupplier(int currentMonth,
int currentYear,
Product [] range) {
//...
productRange = range;
//...
}
Or do a deep copy of the range array, assuming you have either a Product#clone() method or a Product constructor that takes a Product parameter, e.g.
public ElectronicsEquipmentSupplier(int currentMonth,
int currentYear,
Product [] range) {
//...
productRange = new Product[range.length];
for (int i = 0; i < productRange.length; i++) {
productRange[i] = new Product(range[i]);
}
//...
}
The choice between these different methods depends on how the ElectronicsEquipmentSupplier class is used.

Add amount of all person with same id from HashMap

I have a person class
public class Person {
private int id;
private int amount;
public Person(int id, int amount){
this.id = id;
this.amount = amount;
}
//getters
}
And I have a mainClass like this
Map<String, Person> mapOfObjects = new HashMap<String, Person>();
mapOfObjects.put("map1", new Person(1, 1000));
mapOfObjects.put("map2", new Person(1, 1000));
mapOfObjects.put("map3", new Person(1, 1000));
mapOfObjects.put("map4", new Person(2, 1000));
mapOfObjects.put("map5", new Person(2, 1000));
mapOfObjects.put("map6", new Person(3, 1000));
Map<Integer, Integer> mapOfSum = new HashMap<Integer, Integer>();
int sum = 0;
List list = new LinkedList(mapOfObjects.keySet());
for (int i = 0; i < mapOfObjects.size(); i++) {
for (int j = 1; j < mapOfObjects.size() - i; j++) {
if (mapOfObjects.get(list.get(i)).getId() ==
mapOfObjects.get(list.get(j)).getId()) {
sum += (mapOfObjects.get(list.get(i)).getAmount() +
mapOfObjects.get(list.get(j)).getAmount());
}
mapOfSum.put(mapOfObjects.get(list.get(i)).getId(), sum);
}
}
System.out.println(mapOfSum);
It gives me output:
{1=8000, 2=8000, 3=0}
but i want something like this
id=1 amount =3000, id =2 amount = 2000, id =3 amount =1000
How can i remove the object from the map whose summation is already done once while running the first for-loop
Your loop is overengineered.
Try this:
for (Person person : mapOfObjects.values()) //for every person in the map...
{
int newAmount = 0;
if (mapOfSum.containsKey(person.getId())) //if its already in the sumMap
{
newAmount = mapOfSum.get(person.getId()) + person.getAmount(); //update the value
}
else
{
newAmount = person.getAmount(); //else set it as starting value
}
mapOfSum.put(person.getId(), newAmount); //put it in the sum map. If it's already there it will be substituted by new entry.
}
Output:
{1=3000, 2=2000, 3=1000}
EDIT
If you want the output in different format you can do something like this:
StringBuilder stringBuilder = new StringBuilder("");
for (Map.Entry<Integer, Integer> entry : mapOfSum.entrySet())
{
stringBuilder.append("id=").append(entry.getKey()).append(" amount=").append(entry.getValue()).append(", ");
}
System.out.println(stringBuilder.toString());
Output:
id=1 amount=3000, id=2 amount=2000, id=3 amount=1000,
EDIT2:
As suggested in comments by #NickHolt there is more efficient way that shortens execution time by eliminating the containsKey() check.
It can be done like this:
Integer personAmount = mapOfSum.get(person.getId());
if (personAmount == null)
{
personAmount = person.getAmount();
}
else
{
personAmount = person.getAmount() + personAmount;
}
mapOfSum.put(person.getId(), personAmount);
or in shorter form using ternary operator:
Integer personAmmount = mapOfSum.get(person.getId());
personAmmount = personAmmount == null ? person.getAmount() : person.getAmount() + personAmmount;
mapOfSum.put(person.getId(), personAmount);
You can use Google Guava multimap
Multimap<Integer, Integer> PersonMap = ArrayListMultimap.create();
PersonMap.put(1, 1000);
PersonMap.put(1, 1000);
PersonMap.put(1, 1000);
PersonMap.put(2, 1000);
PersonMap.put(2, 1000);
PersonMap.put(3, 1000);
Then you can use something like:
Hashset<Integer, Integer> PersonDictionary = new Hashset<Integer, Integer>();
for (Integer key: PersonMap.keySet())
PersonDictionary.Add(key, Sum(PersonMap.get(key)));
Where sum a function : Is there possibility of sum of ArrayList without looping
Instead of using two for loops, use single, for traversing the value set of the map, and find the summation
Map<String, Person> mapOfObjects = new HashMap<String, Person>();
mapOfObjects.put("map1", new Person(1, 1000));
mapOfObjects.put("map2", new Person(1, 1000));
mapOfObjects.put("map3", new Person(1, 1000));
mapOfObjects.put("map4", new Person(2, 1000));
mapOfObjects.put("map5", new Person(2, 1000));
mapOfObjects.put("map6", new Person(3, 1000));
Map<Integer, Integer> mapOfSum = new HashMap<Integer, Integer>();
for (Person person : mapOfObjects.values()) {
Integer value= mapOfSum.get(person.getId());
if (value == null) {
value = 0;
}
value += person.getAmount();
mapOfSum.put(person.getId(), value);
}
System.out.println(mapOfSum);

using a JButton actionperformed class how do I add elements from one arraylist to another arraylist?

I have a method that returns an arraylist which i am calling via a buttonListener. I need to be able to store each pushes resulting arraylist in another arraylist. How do I do this? Each time i try, it copies over the existing elements in the arraylist I'm using to keep track of push results.
private class ButtonListener implements ActionListener{
public void actionPerformed (ActionEvent e){
numCounter++;
String reqVal1 = requestor.getText();
int reqVal = Integer.parseInt(reqVal1);
request = reqVal;
requestsArray.get(3).set(0,0);
if(numCounter == 1){//---------------------------numCounter == 1 beginning-------- -------------------------
workingVar = memSize/2;
if(request>workingVar){
requestsArray.get(3).set(0,1);
}
else{
reqCounter++;
while (workingVar>=request){
workingVar = workingVar/2;
holes2.add(workingVar);
}
if(workingVar<request){
workingVar=workingVar*2;
holes2.add(workingVar);
holes2.remove(holes2.size()-2);
holes2.remove(holes2.size()-1);
}
}
e1=workingVar;
}//-----------------------------------------------end of numCounter == 1 section-------------------------------------
if(numCounter > 1){
for (int y = 0; y<requestsArray.get(0).size();y++){
if(requestsArray.get(1).get(y).equals("H")){
holes.add((Integer)requestsArray.get(0).get(y));
}
}
//BubbleSort of holes ArrayList
int in, out;
for(out= holes.size()-1; out>0;out--)
for(in =0; in<out;in++)
if(holes.get(in)<holes.get(in+1)){
int temp1 = holes.get(in+1);
int temp2 = holes.get(in);
holes.set(in, temp1);
holes.set(in+1, temp2);
}
//calculates the value of e1 using holes array
if(holes.isEmpty()){
requestsArray.get(3).set(0, 1);
}
else{
for(element=holes.size()-1;element>-1;element--){//starts at end of holes array loops backwards
e1 = holes.get(element); //assigns value of each element to e1
if(e1>=request) //if value e1 is greater than request stop looping
break;
}
workingVar=e1; //assign the value of e1 to workingVar
if (request>e1){
requestsArray.get(3).set(0, 1);
}
else{
//---------------------code for populating holes2 array---------------------------
reqCounter++;
if(workingVar!=request && workingVar/2>=request){
while (workingVar/2>=request){
workingVar = workingVar/2;
holes2.add(workingVar);
}
if(workingVar<request){
workingVar=workingVar*2;
holes2.add(workingVar);
}
}
}
}
}
//Sort of Holes2 ArrayList - reorder's holes2 for initial set up and subsequent inserts
int in, out;
for(out= holes2.size()-1; out>0;out--)
for(in =0; in<out;in++)
if(holes2.get(in)>holes2.get(in+1)){
int temp1 = holes2.get(in+1);
int temp2 = holes2.get(in);
holes2.set(in, temp1);
holes2.set(in+1, temp2);
}
//-------------------------------requestsArray Setups----------------------------------------------------
//Initial setup of requestsArray
if(numCounter == 1){
if(requestsArray.get(3).get(0).equals(0)){
requestsArray.get(0).set(0,e1);
requestsArray.get(1).set(0,"R");
requestsArray.get(2).set(0, reqCounter);;
for(int i = 0; i<holes2.size();i++){
requestsArray.get(0).add(holes2.get(i));
requestsArray.get(1).add("H");
requestsArray.get(2).add(0);
}
}
else{
requestsArray.get(0).set(0,e1);
requestsArray.get(1).set(0, "H");
requestsArray.get(2).set(0,0);
}
}
//Subsequent setup of requestsArray
int element2;
if(numCounter >1 && requestsArray.get(3).get(0).equals(0)){
for(element2 = 0; element2< requestsArray.get(0).size(); element2++){
if((Integer)requestsArray.get(0).get(element2)==e1 &&requestsArray.get(1).get(element2).equals("H") ){
break;
}
}
if(holes2.isEmpty()){
requestsArray.get(1).set(element2, "R");
requestsArray.get(2).set(element2, reqCounter);
}
else{ //holes2 is not empty
requestsArray.get(0).add(element2, workingVar);
requestsArray.get(2).add(element2,reqCounter);
requestsArray.get(1).add(element2, "R");
requestsArray.get(0).remove(element2+1);
requestsArray.get(2).remove(element2+1);
requestsArray.get(1).remove(element2+1);
for(int i = 1; i<holes2.size()+1;i++){
requestsArray.get(0).add(element2+i,holes2.get(i-1));
requestsArray.get(1).add(element2+i,"H");
requestsArray.get(2).add(element2+i,0);
}
}
}
//-----------------End Section for populating requestsArraywhen numCounter > 1---------------------------
//remove all values from holes1 and holes2
holes.clear();
holes2.clear();
System.out.println(results1);
ok. I have written a similar program that is simpler and easier to understand. Each time the button is pressed, the result is saved as an arrayList to another arrayList. Problem is it's appending it to the previous element. I need to be able to add the results of each press as a separate element. For example:
first press:
[5, 3, 5, 2, 6, 5]
second press would display:
[5, 3, 5, 2, 6, 5][2, 1, 4, 1, 4, 1]
This way I can loop through and get each array result separately. How do I do this?
public class mainClass{
public static void main(String[] args){
JFrame frame1 = new JFrame("testButton");
frame1.setDefaultCloseOperation(JFrame. EXIT_ON_CLOSE);
buttonExample b1 = new buttonExample();
frame1.getContentPane().add(b1);
frame1.pack();
frame1.setVisible(true);
}
}
public class Example {
private int rand1;
private ArrayList<ArrayList> count;
private ArrayList<Integer> count2;
private Random rnd;
private int counter1;
private ArrayList<ArrayList>count3;
public Example(){
count = new ArrayList<ArrayList>();
count2 = new ArrayList<Integer>();
rnd = new Random();
count3 = new ArrayList<ArrayList>();
}
private void addCount2(){
for(int x = 0; x<6;x++){
rand1 = rnd.nextInt(6)+1;
count2.add(rand1);// count2 == Integers
}
}
public void addCount(){
addCount2();
count.add(count2);// count == count3
}
public ArrayList<ArrayList> displayCount(){
return count;
}
}
public class buttonExample extends JPanel {
private JButton button1;
private Example example1;
public buttonExample(){
button1 = new JButton("Submit");
add(button1);
button1.addActionListener(new ButtonListener());
example1 = new Example();
}
private class ButtonListener implements ActionListener{
public void actionPerformed(ActionEvent e) {
example1.addCount();
System.out.println(example1.displayCount().get(0));;
}
}
}
I would think about at least two solutions...
create a List<...> list which will last (global variable or something similar, depends on your needs) and use list.addAll() method
create a Map<String, List<...> map and than you can log your lists separately, your key might be a timestamp for example
Well, now when you posted the code you will have to start with a different thing - refactoring. Your code is very long, difficult to read and error prone. You have to think about it a little bit a rewrite it. And trust me, the more effort you put into your code at the beginning the better it will be at the end. Otherwise you may end up with an unmanagable code full of bugs...

Categories