Using Collections and HashMap - java

I have the following class, its fairly simple, all i am doing is storing the variables from a URL.
class RM {
private String identifier, visible;
public String getIdentifier() {
return identifier;
}
public void setIdentifier(String identifier) {
this.identifier = identifier;
}
public String getVisible() {
return visible;
}
public void setVisible(String visible) {
this.visible = visible;
}
public RM (String identifier, //1
String visible; {
this.identifier = identifier; //1
this.visible = visible;
}
#Override
public String toString() {
return identifier + "\t" + visible + "\t";
}
}
This is stored in a collection List when i pass through the variables.
Collection<RM> attributes1 = new ArrayList<>();
I then obtain the variables stored in the identifier field and store them in an array like below:
Object rowDataprelim1 [] = new Object[1];
RM rm = null;
Iterator<RM> iterator = attributes1.iterator();
while(iterator.hasNext()) {
rm = iterator.next();
rowDataprelim1[0] = rm.identifier;
System.out.println(rm.identifier);
I then create a HashMap, the reason for doing so is because i want unique entries only.
Map<Object, Integer> numberMapping = new HashMap<>();//create a new hashmap
And also create an array of which i store identifier into rowData[0].
Object rowData[] = new Object[2];
Iterator it = numberMapping.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry) it.next();
rowData[0] = attributes1.get((int) pair.getValue()).identifier;
it.remove();
}
What i cant get right is the syntax to get the value of identifier from my collections list, i believe the syntax i have used is for an Arraylist.
rowData[0] = attributes1.get((int)pair.getValue()).identifier;
Can someone advise the correct syntax, i only want to get identifier and not the visible. I in fact have around 30 items in my class and only want to get 12 of them for the first section of my project. I have never used collection before and i have been told to use Collection and not ArrayList.
Any help is much appreciated.

Related

Java nested Iterator throws IllegalStateException

I have four different ArrayLists. I want to try out every possible combination of values.
If the first combination doesn't result in something that fulfills my constraints, I want to remove the first value from the first list and do the whole thing again with the next value.
I made an Iterator for each ArrayList but when I remove a value from the first ArrayList, it throws an IllegalStateException.
This is my code:
public static boolean revise(Haus haus1, Haus haus2) {
boolean removed = false;
Iterator<String> iteratorFarbe1 = haus1.getFarbListe().iterator();
while (iteratorFarbe1.hasNext()) {
String farbe1 = iteratorFarbe1.next();
Iterator<String> iteratorFarbe2 = haus2.getFarbListe().iterator();
while (iteratorFarbe2.hasNext()) {
String farbe2 = iteratorFarbe2.next();
Iterator<String> iteratorLand1 = haus1.getLandListe().iterator();
while (iteratorLand1.hasNext()) {
String land1 = iteratorLand1.next();
Iterator<String> iteratorLand2 = haus2.getLandListe().iterator();
while (iteratorLand2.hasNext()) {
String land2 = iteratorLand2.next();
Haus checkHaus1 = new Haus(haus1.getNummer(), farbe1, land1);
Haus checkHaus2 = new Haus(haus2.getNummer(), farbe2, land2);
if (!checkConstraints(checkHaus1, checkHaus2)) {
iteratorFarbe1.remove();
removed = true;
}
}
}
}
}
return removed;
}
This could happen because teratorFarbe1.remove() called more than once between two calls of iteratorFarbe1.hasNext()

Using a splitter on an Iterated LinkedList?

Just wondering if you can use a splitter class to split up details moved from a LinkedList to and iterated one? This is the code of the initial split I used before I iterated the LinkedList:
Scanner input = new Scanner(new File("today.txt"));
while (input.hasNextLine())
{
names = input.nextLine();
if(names.contains(":"))
{
splitter2 = names.split(":");
name = splitter2[0];
times = splitter2[1];
System.out.printf("%s\t\t %s \n",name, times);
}
q1.add(names);
}
Q1 being the LinkedList that i have created.
Is there anyway to split the iterated list so that i can only search for name when calling back the new Iterated List?
If I understand you correctly, a Map would suit your needs better than a LinkedList.
You can have a Map<String,String> where the key is name and the value is times. Or you can have a Map<String,SomeObject> where the key is the name and the value some object that contains the data you read from the line.
Then, instead of q1.add(names), you can have :
Map<String,String> map = new HashMap<>();
...
while (input.hasNextLine()) {
...
map.put (name,times);
...
}
or
Map<String,SomeObject> map = new HashMap<>();
...
while (input.hasNextLine()) {
...
map.put (name,new SomeObject(name,times);
...
}
Later you can search the map for a specific name (map.containsKey(name) or map.get(name)), or iterate over all the names (using map.keySet()).
This is a little unclear, but I think what you're looking for is a HashMap. If the idea is to put the names and times into a data structure so that you can later search by name, then you want a HashMap<String,String> map, and then
map.put(name,times);
to add to the map. Later on, you can retrieve the times for a particular name with
map.get(name);
There are some assumptions here:
You don't care about the order of the names (see LinkedHashMap if you do care).
The names are unique (see Guava's Multimap if they're not unique).
You can create a custom Class, change q1 to a list of this type, add the elements if they can be split.
final List<Person> q1=new LinkedList<Person>();
{...other code...}
//your code change to add to this list when split can occur
if(names.contains(":"))
{
splitter2 = names.split(":");
name = splitter2[0];
times = splitter2[1];
System.out.printf("%s\t\t %s \n",name, times);
q1.add(new Person(name,times);
}
Then you can iterate the list and compare the attribute name with a search key:
final String searchKey="george";
for(final Person person : q1){
if(person.getName().equalsIgnoreCase(searchKey))
System.out.println("I found " + searchKey +"!");
}
Person class:
public class Person {
private String name;
private String time;
public Person(String name, String time) {
this.name = name;
this.time = time;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setTime(String time) {
this.time = time;
}
public String getTime() {
return time;
}
}
Alternatively, you can iterate and split the String only list, during the iteration, in the same way you did before. The previous method is better.
Example:
public static void main(String[] args) {
final String search = "george";
List<String> q1 = new LinkedList<String>();
q1.add("tom:120000");
q1.add("george:130000");
q1.add("john:120000");
for (final String q : q1) { //for each string q in the list q1
if (q.contains(":")) {
final String[] split = q.split(":");
final String name = split[0];
final String time = split[1];
if (name.equalsIgnoreCase(search)) {
System.out.println("I found " + search + "!");
System.out.println(name + " : " + time);
break;
}
}
}
}

java.lang.String cannot be cast to [Ljava.lang.Object;

I want to call course name in combobox and print course Id which selected coursename How can I solve this problem?
public void coursename(){
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
Query query= session.createQuery("select a.courseName,a.courseId from Semester e inner join e.course as a");
for (Iterator it = query.iterate(); it.hasNext();) {
Object row[] = (Object[]) it.next();
combocourse.addItem(row[0]);
}
session.close();
}
private void combocourseActionPerformed(java.awt.event.ActionEvent evt) {
JComboBox combocourse = (JComboBox)evt.getSource();
Object row[] = (Object[])combocourse.getSelectedItem();
System.out.println("id"+row[1] );
}
By not trying to cast a String to an Object[]. Look at the return value of the methods you're using, and use variables typed appropriately to store those return values. JComboBox#getSelectedItem returns an Object (in this case apparently a String), not an array (of any kind). But in this line:
Object row[] = (Object[])combocourse.getSelectedItem();
...you're trying to cast it to be an Object[] (array of Object) so you can store it in an Object[]. You can't do that.
It seems like row should just be Object or String, not Object[], and that when you use it you should just use it directly, not as row[1]:
Object row = combocourse.getSelectedItem();
System.out.println("id"+row );
Or
String row = (String)combocourse.getSelectedItem();
System.out.println("id"+row );
In a comment you asked:
I called coursename in combobox but i should save course id in my database. How can I get courseId?
I don't know JComboBox. Fundamentally, you need to store something that contains both values (the ID and name) and then use that something when you get the selected item. Unless JComboBox has some functionality for this built in, you might need a simple class for that that holds the values and implements toString by returning courseName. Something vaguely like:
class CourseItem {
private String courseName;
private String courseId; // Or int or whatever
CourseItem(String courseName,String courseId) {
this.courseName = courseName;
this.courseId = courseId;
}
public String getCourseName() {
return this.courseName;
}
public String getCourseId() {
return this.courseId;
}
public String toString() { // For display
return this.courseName;
}
}
Then:
public void coursename() {
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
Query query = session.createQuery("select a.courseName,a.courseId from Semester e inner join e.course as a");
for (Iterator it = query.iterate(); it.hasNext();) {
Object row[] = (Object[]) it.next();
combocourse.addItem(new CourseItem((String)row[0], (String)row[1]));
}
session.close();
}
private void combocourseActionPerformed(java.awt.event.ActionEvent evt) {
JComboBox combocourse = (JComboBox) evt.getSource();
CourseItem item = (CourseItem)combocourse.getSelectedItem();
System.out.println("id" + item.getCourseId());
}
try:
Object row = (Object)combocourse.getSelectedItem();
System.out.println("id"+row );
You only add single objects into the combocourse, not arrays of objects.
combocourse.getSelectedItem(); in your case returns String and string cannot be cast to array of objects. If you want to get List of Objects, they use getSelectedObjects()

how to combine object item and sum up qty - JAVA

i having an object with below information
TransHdr: id, order_num
TransItem: hdr_id, product_code, refnum, qty (child record)
transHdr.id=transItem.hdr_id
if let say 3 record can be found in TransItem,
parkA,112,10
parkA,112,6
parkB,113,10
i would like group it base on refnum, means that my result will be
parkA,112,16
parkB,113,10
i need a method that will loop the object (item level) and need to return transHdr object to other function. anyway to do this?
for (java.util.Iterator<ITransItem> groupTransItems = TransHdr.getTransItems().iterator();
groupTransItems.hasNext();) {
ITransItem _TransItem = groupTransItems.next();
if (null!=_TransItem.getRefNum()){
<question here..how do i group and sum up my item and become only 1 record?>
}
}
return newGroupingTransHdr;
}
Create a new Map with refnum as key and qty as value.
Map<String,Integer> qtyMap=new HashMap<String,Integer>();
while iterating, try
String refNum=transItem.getRefNum();
// Mark for removal ? if this is not the first item in the list with the refnum
boolean remove=true;
Integer currentQty=qtyMap.get(refNum);
if(currentQty==null){
currentQty=0;
// this doesnt exist already in the map, this is the first item with this reference
// number in the list, so you should keep this without removing
remove=false;
}
currentQty=currentQty+transItem.getQty();
qtyMap.put(refNum,currentQty);
// if the remove is true then remove this item from the list.
if(remove){
groupTransItems.remove();
}
This will sum up the qty for refnum's in the map and once your iteration is over, the map will have the sums of quantities for each refnum. You will have to iterate the list once more to set the current qty to each item from the map [EDIT] :- Added the iterating time removal.
Similar to the solution suggested in this post. You can have a Map with ref_num as key and TransItem as value.
TransHdr transHdr; // Externally given
Map<String, ITransItem> collapsedItems = new HashMap<String, ITransItem>();
List<ITransItem> items = transHdr.getItems();
transHdr.setItems(new ArrayList<ItransItem>());
for (ITransItem item : items) {
String ref_num = item.getRefNum();
ITransItem collapsedItem = collapsedItems.get(ref_num);
if (collapsedItem == null) {
collapsedItems.put(ref_num, item);
} else {
int qnt = item.getQnt();
collapsedItem.setQnt(collapsedItem.getQunt() + qnt);
}
}
transHdr.setItems(new ArrayList<ITransItem>(collapsedItems.values()));
Another way to accomplish what you want to do is to embed the logic in an add method on your TransHdr class.
pulic class TransHdr {
private String id;
private int orderNumber;
private Map<String, ITransItem> items;
public TransHdr(String id, int orderNumber) {
this.id = id;
this.orderNumber = orderNumber;
this.items = new HashMap<String, ITransItem>();
}
public void addItem(ITransItem item) {
String ref = item.getRefNum();
ITransItem currentItem = items.get(ref);
if (currentItem == null) {
items.put(ref, item);
} else {
int qnt = item.getQnt();
currentItem.setQnt(currentItem.getQnt() + qnt);
}
}
public Set<ITransItem> getItems() {
return items.values();
}
}
As you can see, there's multiple ways of doing this. The appropriate solution depends on what your requirements and use cases are.

Convert an ArrayList to an object array

Is there a command in java for conversion of an ArrayList into a object array. I know how to do this copying each object from the arrayList into the object array, but I was wondering if would it be done automatically.
I want something like this:
ArrayList<TypeA> a;
// Let's imagine "a" was filled with TypeA objects
TypeA[] array = MagicalCommand(a);
Something like the standard Collection.toArray(T[]) should do what you need (note that ArrayList implements Collection):
TypeA[] array = a.toArray(new TypeA[a.size()]);
On a side note, you should consider defining a to be of type List<TypeA> rather than ArrayList<TypeA>, this avoid some implementation specific definition that may not really be applicable for your application.
Also, please see this question about the use of a.size() instead of 0 as the size of the array passed to a.toArray(TypeA[])
You can use this code
ArrayList<TypeA> a = new ArrayList<TypeA>();
Object[] o = a.toArray();
Then if you want that to get that object back into TypeA just check it with instanceOf method.
Yes. ArrayList has a toArray() method.
http://java.sun.com/javase/6/docs/api/java/util/ArrayList.html
Convert an ArrayList to an object
array
ArrayList has a constructor that takes a Collection, so the common
idiom is:
List<T> list = new ArrayList<T>(Arrays.asList(array));
Which constructs a copy of the list created by the array.
now, Arrays.asList(array) will wrap the array, so changes to the list
will affect the array, and visa versa. Although you can't add or remove
elements from such a list.
TypeA[] array = (TypeA[]) a.toArray();
Using these libraries:
gson-2.8.5.jar
json-20180813.jar
Using this code:
List<Object[]> testNovedads = crudService.createNativeQuery(
"SELECT cantidad, id FROM NOVEDADES GROUP BY id ");
Gson gson = new Gson();
String json = gson.toJson(new TestNovedad());
JSONObject jsonObject = new JSONObject(json);
Collection<TestNovedad> novedads = new ArrayList<>();
for (Object[] object : testNovedads) {
Iterator<String> iterator = jsonObject.keys();
int pos = 0;
for (Iterator i = iterator; i.hasNext();) {
jsonObject.put((String) i.next(), object[pos++]);
}
novedads.add(gson.fromJson(jsonObject.toString(), TestNovedad.class));
}
for (TestNovedad testNovedad : novedads) {
System.out.println(testNovedad.toString());
}
/**
* Autores: Chalo Mejia
* Fecha: 01/10/2020
*/
package org.main;
import java.io.Serializable;
public class TestNovedad implements Serializable {
private static final long serialVersionUID = -6362794385792247263L;
private int id;
private int cantidad;
public TestNovedad() {
// TODO Auto-generated constructor stub
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getCantidad() {
return cantidad;
}
public void setCantidad(int cantidad) {
this.cantidad = cantidad;
}
#Override
public String toString() {
return "TestNovedad [id=" + id + ", cantidad=" + cantidad + "]";
}
}

Categories

Resources