Java get elements that are not in an arraylist - java

I am trying to add users to a model.
I want to add all the users that are in MembersArray but not in membersAvailableArray.
membersAvailableArray = all members in the class.
MembersArray = all members
Im trying to get all members that are in MembersArray but not membersAvailableArray
DefaultListModel<String> model2 = new DefaultListModel<>();
for(Member allMems: MembersArray)
{
for(Member mems: membersAvailableArray)
{
if(!allMems.getUsername().equals(mems.getUsername()))
{
model2.addElement(allMems.getFirstName() + " " + allMems.getLastName());
}
}
}
availableMembersJList.setModel(model2);

You do not need any looping here, just some good old "All" operations:
ArrayList<Member> membersToAdd = members.clone();
membersToAdd.removeAll(availableMembers);
membersToAdd now has all the members you need to add.
If you happen to have Java 8, there is an even simpler way to do this:
members.stream()
.filter(p->!availableMembers.contains(p))
.forEach(p->model2.addElement(p));

try this tricky way, add all to an ArrayList and remove those you do not want
ArrayList<Member> tmp = new ArrayList<Member>();
tmp.addAll(MembersArray);
tmp.removeAll(membersAvailableArray);
for(Member allMems: tmp){
model2.addElement(allMems.getFirstName() + " " + allMems.getLastName());
}

Related

Saving Inputs to ArrayList

So I am making a project and I want to create a new clinic.
On my UI we insert all the topics that we need to create the clinic and they must be saved as ArrayList and I am struggling with this method.
this is how i am asking for the input, should i change to a scanner?
laboratoryId = Utils.readLineFromConsole("Enter Clinic Id: ");
class to the array
public class ClinicalAnalysisLabStore{
private ArrayList<ClinicalAnalysisLab> cliniclist;
public ClinicalAnalysisLabStore(){
cliniclist = new ArrayList<>();
}
public ArrayList<ClinicalAnalysisLab> getCliniclist() {
return cliniclist;
}
cals = new ClinicalAnalysisLabStore();
ArrayList<ClinicalAnalysisLab> cliniclist = cals.getCliniclist();
for(ClinicalAnalysisLab cals : cliniclist){
System.out.print(cals.getLaboratoryId()+"\n");
System.out.print(cals.getName()+ "\n");
System.out.print(cals.getAddress()+"\n");
System.out.print(cals.getPhoneNumber()+"\n");
System.out.print(cals.getTinNumber()+"\n");
System.out.print(cals.getTestType()+"\n");
}
Utils.readLineFromConsole("The Operation was a success!");
this is a short cut from my code where i am trying to print the arraylist but it only prints "The Operation was a success!"
You're ArrayList is empty. So, the code is actually working perfectly.
What you'll need to do is add items to the ArrayList.
To add an item:
laboratoryId = Utils.readLineFromConsole("Enter Clinic Id: ");
ClinicalAnalysisLab obj = new ClinicalAnalysisLab(laboratoryId, *name*, *address*, *phoneNumber*, *tinNumber*) {
clinicList.add(obj);
In this case, you would just create the object based on however you want. So, change the variables "name", "address", "phoneNumber", and "tinNumber" with whatever you want.
One example would be:
laboratoryId = Utils.readLineFromConsole("Enter Clinic Id: ");
ClinicalAnalysisLab obj = new ClinicalAnalysisLab(laboratoryId, "First Lab", "32 Lincoln Rd", "666 666 6666, "102") {
clinicList.add(obj);

How to make a Arraylist with JSON Objects in JAVA?

I want to make a Arraylist with JSON Objects .
There is a loop which gives me JSON Objects. I want to put them into a ArrayList.
Here is the Code which gives me JSON Objects. Please let me know how to put all the values ito a ArrayList
for (int i=0; i<10; i++) {
String datapointsBodyString = "{items:[{id:" + unionUptimeMetadata.getLatencyTimeseriesIds().get(i) + ", start: " + oldestTimeString + ",end: " + now + ", granularity: 1m}]}";
JSONObject datapointsBodyObject = new JSONObject((datapointsBodyString));
HttpResponse uptimeResponse = httpService.POST("url", datapointsBodyObject.toString(), unionUptimeTimeseriesHeaders);
HttpEntity uptimeResponseEntity = uptimeResponse.getEntity();
String uptimeResponseString = EntityUtils.toString(uptimeResponseEntity);
JSONObject uptimeResponsObject = new JSONObject(uptimeResponseString);
}
Thanks in advance.
It's generally worth doing a search for common programming tasks. You could just google search "java add to list" which should result in something like:
List<JSONObject> myList = new ArrayList<>();
myList.add(uptimeResponsObject);
that should be enough for you to get it working.

Swing - Updating element in JList after modifing it in another frame

I have the following code
DefaultListModel<String> modelPacientes = new DefaultListModel<>();
JList <String> listPacientes = new JList<>( modelPacientes );
listPacientes.setToolTipText("Lista de los pacientes del doctor");
GridBagConstraints gbc_listPacientes = new GridBagConstraints();
gbc_listPacientes.fill = GridBagConstraints.BOTH;
gbc_listPacientes.gridx = 0;
gbc_listPacientes.gridy = 0;
pPacientes.add(listPacientes, gbc_listPacientes);
modelPacientes.addElement(raul.getName() + " " + raul.getSurname());
modelPacientes.addElement(paula.getName() + " " + paula.getSurname());
modelPacientes.addElement(sara.getName() + " " + sara.getSurname());
I am modifying the values of the objects (raul, paula and sara) in another frame, how could I update it in the JList or anywhere else (JLabel) after closing the other frame?
I am modifying the values of the objects
Then the ListModel should contain the Objects not a String. So assuming your Objects are of type User you would do something like:
DefaultListModel<User> modelPacientes = new DefaultListModel<User>();
JList<User> listPacientes = new JList<User>( modelPacientes );
modelPacientes.addElement(raul);
modelPacientes.addElement(paula);
modelPacientes.addElement(sara);
Then in the User class you can override the toString() method to return the value you want to display in the JList:
#Override
public String toString()
{
return getName() + " " + getSurname();
}
I am modifying the values of the objects (raul, paula and sara) in another frame
Then you get the User object you want to modify from the ListModel and pass this object to your JDialog (note you should be using a JDialog, not a JFrame for a popup child window).
Then you update the data in the User object and when the dialog closes you invoke repaint() on the JList.
You can either provide your own subclass of ListModel (or DefaultListModel) that returns patient.getName() + " " + patient.getSurname()) in method getElementAt
or you can move the creation of the modelPacientes to a new method:
ListModel createModel() {
DefaultListModel<String> modelPacientes = new DefaultListModel<>();
modelPacientes.addElement(raul.getName() + " " + raul.getSurname());
modelPacientes.addElement(paula.getName() + " " + paula.getSurname());
modelPacientes.addElement(sara.getName() + " " + sara.getSurname());
return modelPacientes;
}
then build an empty JList instead and run listPacientes.setModel(createModel()) whenever the pacientes have changed.
This approach is fine if you have a couple dozens patients.
If you have hundreds or thousands of patients, it is probably worthwhile to you have your own model classes that map from your patient data into whatever the Swing component needs.
Add the objects (raul, paula and sara) to the list modal. Then create a ListCellRenderer that will return a string that is the "display name" for example:
raul.getName() + " " + raul.getSurname()
That way when the name of raul, paula and/or sara changes it will automatically change in the list if it is the same instance of the object.

Mapping several columns from sql to a java object

I am trying to retrieve and process code from JIRA, unfortunately the pieces of information (which are in the Metadata-Plugin) are saved in a column, not a row.
Picture of JIRA-MySQL-Database
The goal is to save this in an object with following attributes:
public class DesiredObject {
private String Object_Key;
private String Aze.kunde.name;
private Long Aze.kunde.schluessel;
private String Aze.projekt.name;
private Long Aze.projekt.schluessel
//getters and setters here
}
My workbench is STS and it's a Spring-Boot-Application.
I can fetch a List of Object-Keys with the JRJC using:
JiraController jiraconnect = new JiraController();
List<JiraProject> jiraprojects = new ArrayList<JiraProject>();
jiraprojects = jiraconnect.findJiraProjects();
This is perfectly working, also the USER_KEY and USER_VALUE are easily retrievable, but I hope there is a better way than to perform
three SQL-Searches for each project and then somehow build an object from all those lists.
I was starting with
for (JiraProject jp : jiraprojects) {
String SQL = "select * from jira_metadata where ENRICHED_OBJECT_KEY = ?";
List<DesiredObject> do = jdbcTemplateObject.query(SQL, new Object[] { "com.atlassian.jira.project.Project:" + jp.getProjectkey() }, XXX);
}
to get a list with every object, but I'm stuck as i can't figure out a ObjectMapper (XXX) who is able to write this into an object.
Usually I go with
object.setter(rs.getString("SQL-Column"));
But that isn't working, as all my columns are called the same. (USER_KEY & USER_VALUE)
The Database is automatically created by JIRA, so I can't "fix" it.
The Object_Keys are unique which is why I tried to use those to collect all the data from my SQL-Table.
I hope all you need to enlighten me is in this post, if not feel free to ask for more!
Edit: Don't worry if there are some 'project' and 'projekt', that's because I gave most of my classes german names and descriptions..
I created a Hashmap with the Objectkey and an unique token in brackets, e.g.: "(1)JIRA".
String SQL = "select * from ao_cc6aeb_jira_metadata";
List<JiraImportObjekt> jioList = jdbcTemplateObject.query(SQL, new JiraImportObjektMapper());
HashMap<String, String> hmap = new HashMap<String, String>();
Integer unique = 1;
for (JiraImportObjekt jio : jioList) {
hmap.put("(" + unique.toString() + ")" + jio.getEnriched_Object_Key(),
jio.getUser_Key() + "(" + jio.getUser_Value() + ")");
unique++;
}
I changed this into a TreeMap
Map<String, String> tmap = new TreeMap<String, String>(hmap);
And then i iterated through that treemap via
String aktuProj = new String();
for (String s : tmap.keySet()) {
if (aktuProj.equals(s.replaceAll("\\([^\\(]*\\)", ""))) {
} else { //Add Element to list and start new Element }
//a lot of other stuff
}
What I did was to put all the data in the right order, iterate through and process everything like I wanted it.
Object hinfo = hmap.get(s);
if (hinfo.toString().replaceAll("\\([^\\(]*\\)", "").equals("aze.kunde.schluessel")) {
Matcher m = Pattern.compile("\\(([^)]+)\\)").matcher(hinfo.toString());
while (m.find()) {
jmo[obj].setAzeKundeSchluessel(Long.parseLong(m.group(1), 10));
// logger.info("AzeKundeSchluessel: " +
// jmo[obj].getAzeKundeSchluessel());
}
} else ...
After the loop I needed to add the last Element.
Now I have a List with the Elements which is easy to use and ready for further steps.
I cut out a lot of code because most of it is customized for my problem.. the roadmap should be enough to solve it though.
Good luck!

Accessing arraylist in another class

Hi i have an arraylist that i want to access from another class, i'm new to android please try to explain in a simple way
//Adding item to ArrayList
Cursor cursor2=shoppingListDB.rawQuery("SELECT * FROM " + selected_spinner + ";", null);
if (cursor2.moveToFirst()){
list.clear();
do{
String itemName = cursor2.getString(cursor2.getColumnIndex("ITEM_NAME"));
String shopList = cursor2.getString(cursor2.getColumnIndex("SHOP_LIST"));
String numbItems = cursor2.getString(cursor2.getColumnIndex("NUMB_ITEMS"));
//Adding Items to the arraylist
list.add(numbItems + " x"+ " " +itemName + " " + "#"+shopList);
}
while (cursor2.moveToNext());
//====CODE FOR SHOWING DATA AS A SIMPLE LIST ITEM=========================================
view_list = (ListView)findViewById(R.id.listItems);
ArrayAdapter <String> adapter=new ArrayAdapter<String>(CreateList.this,android.R.layout.simple_list_item_1,list);
view_list.setAdapter(adapter);
}
else{
Toast.makeText(getApplicationContext(), "DATA NOT AVAILABLE", 3000).show();
}
cursor2.close();
I think you should use basic OOP concept for this.
in your class you can declare the list as class instance variable and use getter method to get the list in other class.
public class abcd {
private List<String> list;
public List<String> getList() {
return list;
}
//your code which uses list
}
Hope this will help you.

Categories