what i'm trying to do with the method below is look for a specific student in an array list that where the name and unique number(HUN) match the key and keyInt respectively. Once that student is found it should add to the local array list returnStudent and return it. However the line returnStudent.add(student(i)); is giving me an error and i can't figure out how to fix it,i need it to add the specific student to the local array list.
public ArrayList<Student1> searchByKey(String key, int keyInt)
{
ArrayList<Student1> returnStudent = new ArrayList<Student1>();
Student1 student = new Student1(key);
int i = 0;
while(i <= students.size())
{
if(student.getName().equals(key) && student.getHUN() == keyInt)
{
return Student.add(student(i));
}
i=i+1;
}
return returnStudent;
}
Thanks in advance.
Change
returnStudent.add(student(i));
to
returnStudent.add(student); // student is the element
to add to a specific index, use -
returnStudent.add(i, student); // i is the index to add element at
Note - since you have initialized i=0 you shall iterate through i < students.size() or you might end up accessing get(i) on the list for the value that doesn't exist (base indexed to 0).
The other way to do what you are trying to achieve is using Java8 as -
ArrayList<Student1> students = new ArrayList<>();
public ArrayList<Student1> searchByKey(String key, int keyInt) {
ArrayList<Student1> returnStudent = new ArrayList<>();
Student1 student = new Student1(key);
students.forEach(element -> {
if (element.getName().equals(key) && element.getHUN() == keyInt) {
returnStudent.add(element);
}
});
return returnStudent;
}
Assuming students is an ArrayList with prepopulated data, you can do the following.
public ArrayList<Student1> searchByKey(String key, int keyInt) {
ArrayList<Student1> returnStudent = new ArrayList<Student1>();
for(Student1 student1 : students) {
if(student1.getName().equals(key) && student1.getHUN() == keyInt) {
returnStudent.add(student1);
}
}
return returnStudent;
}
I have changed the while loop to foreach loop to make it look simpler and easily understandable.
You loop through students. But add student(i). Note the s at the end. Change the add to students(i).
Related
I have an array where i get the values as names of some students and the array is dynamically populates and it does not contain static values. Now what i want to check is that whether the array obtained has any same name. Here is some part of my code,
ArrayList<Student> rows;
for (Student name: rows) {
}
I dont know how to check. I have used compartor but it didnt work. Can anyone help. Inside the array I will get all student names
Use a list to store any duplicate names:
List<String> dups = new ArrayList<>();
and a set where you will store names:
Set<String> names = new HashSet<>();
A set contains only unique values.
Now iterate through your list
(I guess your Student class has a method like getName() to obtain the student's name):
for (Student student : rows) {
String studentname = student.getName();
if (!names.add(studentname) {
dups.add(studentname);
}
}
The method names.add() returns false when it's not possible for an item to be added to the set because it already exists in it.
So when it returns false it encountered a duplicate name and the name is added to the dups list.
When this loop finishes, you can find all the duplicate student names in the dups list and show them in a toast:
if (dups.size() > 0) {
StringBuilder sb = new StringBuilder("There are duplicates: ");
for (String studentname : dups) {
sb.append(studentname).append(", ");
}
String msg = sb.toString();
msg = msg.substring(0, msg.length() - 2);
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
}
A way to check it is to convert your list to a set and check if the size got reduced (because Sets do not accept duplicate values), something like :
ArrayList<Student> rows;
Set<Student> set = new HashSet<Student>(rows);
if(set.size() < rows.size()){
// In this case you have repeated values in the list
}
Note that it depends on your equals method of the Student class to determine how Students are compared, so since you are checking againist their names you might have this equals method inside your Student class:
#Override
public boolean equals(Object obj) {
if( obj instanceof Student) {
return (obj.name.equals(name));
}
return false;
}
Store the data in HashMap with key as studentName and value as student object
Map studentMap = new HashMap<>()
If you add the data with same key again , the data gets updated
studentMap.put(studentName, Student)
To check if key exists and update accordingly
if(studentMap.containsKey(studentName)){
// logic if key already exists
}else{
//logic if key doesn't exists
}
If you want list instead of map , then get list from map
List studentList = new ArrayList(studentMap.values())
Check this sample java class used to count no of duplicate elements.
public class CountDuplicate {
public static void main(String[] args) {
ArrayList<String> arrayList = new ArrayList<String>();
arrayList.add("aaa");
arrayList.add("bbb");
arrayList.add("aaa");
arrayList.add("bbb");
arrayList.add("ccc");
arrayList.add("bbb");
arrayList.add("ccc");
arrayList.add("aaa");
arrayList.add("ccc");
arrayList.add("bbb");
HashSet<String> hsUnique = new HashSet<String>(arrayList);
for (String str : hsUnique) {
System.out.println(Collections.frequency(arrayList, str) +" times "+ str);
}
}
}
I am trying to develop a method which receives a List of ArrayList and classify the array list inside it based on the object value. Then, return array list that contains the objects have 1 in their FirstChoice.
the data structure in my code is that
the List has n number of ArrayList, the ArrayList has 24 objects. each object has 3 elements and FirstChoice is one of these elements.
The problem of my code is the output not as i expect , it seems to be just stick with one value and repeat it for the whole list. could you please help me to fix that
ArrayList<HH> TestMethods(List<ArrayList<HH>> s) {
ArrayList<HH> scenario = new ArrayList<HH>();
for (ArrayList<HH> d : s) {
for (int i = 0; i < d.size(); i++) {
if (s.get(i).get(i).FirstChoice == 1) {
scenario.add(s.get(i).get(i));
}
}
}
return scenario;
}
The problem in your code is that when you are looping over the list s, you are actually never using the current element d.
Some other comments on your code:
Prefer returning a List instead of an ArrayList.
Name your methods and variables according to Java naming conventions (testMethods instead of TestMethods, firstChoice instead of FirstChoice)
Be consistent in the way you write loops: use foreach or an index but keep to the same style.
List<HH> testMethods(List<ArrayList<HH>> s) {
List<HH> scenario = new ArrayList<HH>();
for (ArrayList<HH> d : s) {
for (HH hh : d) {
if (hh.firstChoice == 1) {
scenario.add(hh);
}
}
}
return scenario;
}
Your mistakes are on these lines if (s.get(i).get(i).FirstChoice == 1) { and scenario.add(s.get(i).get(i)); as you aren't actually user inner list d.
You're referencing the i'th element of the i'th list of s, when I think you want the i'th element of d where d is a list from s.
ArrayList<HH> TestMethods(List<ArrayList<HH>> s) {
ArrayList<HH> scenario = new ArrayList<HH>();
for (ArrayList<HH> d : s) {
for (int i = 0; i < d.size(); i++) {
int item = d.get(i).FirstChoice;
if (item == 1) {
scenario.add(item);
}
}
}
return scenario;
}
I have list of ObjectLocation, declared as
List<ObjectLocation> myLocations;
And here's how ObjectLocation looks like:
public class ObjectLocation {
int locationID, ratingCount = 0;
}
Ok now myLocations holds thousands of locationID. If I have a particular locationID, how do I search the contents of myLocations for the locationID, and get the searched locationID's index (within myLocations) and it's ratingCount?
Well, you loop through all of the elements in the list, and if the locationID match, you've found your element!
int idx=0;
for (ObjectLocation ol:myLocations){
if (ol.locationID==searchedLocationID){
// found at index idx!!
}
idx++;
}
More efficiently, you could have a Map<Integer,ObjectLocation> where the key is the locationID of the ObjectLocation, to get much faster lookups.
For this sort of lookup I'd switch to using a Map<Integer, ObjectLocation> and store entries in the map like this:
Map<Integer, List<ObjectLocation>> myLocationMap = new HashMap<>();
List<ObjectLocation> currentList = myLocationMap.get(oneLocation.locationID);
if(currentList == null) {
// We haven't stored anything at this locationID yet,
// so create a new List and add it to the Map under
// this locationID value.
currentList = new ArrayList<>();
myLocationMap.put(oneLocation.locationID, currentList);
}
currentList.add(oneLocation);
Now you can quickly get all of the ObjectLocation entries with a specific value for locationID by grabbing them from the map like this:
List<ObjectLocation> listOfLocations = myLocationMap.get(someLocationId);
This assumes that multiple ObjectLocation instances can have the same locationID value. If not then you wouldn't need a List<ObjectLocation> in the map, just a single ObjectLocation.
For you to easily search and find a your ObjectLocation objects, you should first define .equals(Object o) method, in ObjectLocation class, that allows one ObjectLocation to be compared to another. After that, all you have to do is use .indexOf(Object o)' to get the index of the ObjectLocation you are looking for. Then extract that object and use its information as exemplified in the code below:
public class ObjectLocation {
int locationID, ratingCount = 0;
public boolean equals(Object o)
{
if(!(o instanceof ObjectLocation))
return false;
ObjectLocation another = (ObjectLocation)o;
if( locationID == another.locationID && ratingCount == another.ratingCount)
return true;
else
return false;
}
public static void main(String[] args)
{
List<ObjectLocation> myLocations;
ObjectLocation findThisLocation;
ObjectLocation found;
//Additional code here
int index = myLocations.indexOf(findThisLocation);
found = myLocations.get(index);
int id = found.locationID;
int rating = found.ratingCount;
}
}
List<ObjectLocation> myLocations = new ArrayList<>();
int index =0;
int particularId = 1;//!your Id
int locationid = 0;
int ratingcount = 0;
for(int i =0; i < myLocations.size(); i++) {
if(myLocations.get(i).locationID == particularId) {
index = i;
locationid = myLocations.get(i).locationID;
ratingcount = myLocations.get(i).ratingCount;
}
}
For Java 8, I would use (without changing anything on the data structure like using a Map instead or knowing about ordering in the list):
Optional<ObjectLocation> found = myLocations.stream()
.filter(location -> location.locationID == particularLocationID)
.findAny();
if (found.isPresent() {
int ratingCount = found.get();
…
}
When you need more performance for single searches, you may try parallelStream() instead of stream().
I have a list like this
List contains set of dtime,uptime values.I want to get the list items i.e., dtime into one and
uptime into another variable.Likewise I want to get all the dtime and uptime pair values seperatly into
the variables using for loop in java.How can I achieve this.Is it possible list or vector?Please help me.
Pseudo code
List.get(0).get(0)-->gives 1st dtime
List.get(0).get(1)-->gives 1st uptime
List.get(1).get(0)-->gives 2nd dtime
List.get(1).get(1)-->gives 2nd uptime
And so on..
How to implement this with for loop I am not getting.I am new to java>please help me..
First Convert That ArrayList into Object[] array then get the value like given below code...driver_ModelsObj is an array convert that into drives object array then get the value from inside the array.
for(int indx=0;indx<driver_ModelsObj.size();indx++){
Object[] drivers=(Object[]) driver_ModelsObj.get(indx);
String Device_ID=drivers[0].toString();
}
If your list is as below
List list = [[1],[2],[3]];
We can retrieve the each value as below.
((List)list.get(0)).get(0); //This will retrieve value 1
((List)list.get(1)).get(0); //This will retrieve value 2
Sounds like you could use a domain object containing uptime and downtime.
For example,
public class Stats {
int dtime;
int uptime;
}
Then you can have a List<Stats> and access it like this:
mylist.get(0).dtime
mylist.get(0).uptime
mylist.get(1).dtime
mylist.get(1).uptime
Part of the (newer) Collcetions framework, List is almost always a better alternative than Vector
List.get(0).get(0)-->gives 1st dtime
List.get(0).get(1)-->gives 1st uptime
Well, what you're doing here, is getting the list at position 0, and getting item 1 from that list. In a for loop we can express this as:
for(int x = 0; x < List.size(); x++)
{
for(int y = 0; y < List.get(x).size(); y++)
{
if(y % 2 == 0)
{
// It's a dtime object.
}
else
{
// It's an uptime object.
}
}
}
Before this, you could declare some lists of your own:
List<DTime> listD = new ArrayList<ATimeObject>();
List<UpTime> listUp = new ArrayList<UpTime>();
Now when you're cycling through, all you need to do is add the relevant object:
if(y % 2 == 0)
{
listD.add(List.get(x).get(y));
}
else
{
listUp.add(List.get(x).get(y));
}
You should create a POJO like
public class TimeData {
double dtime;
Date uptime;
}
Then add each POJO to array list and then iterate it.
List<TimeData> oList = new ArrayList<TimeData>();
int nSize = oList.size();
for(int i=0;i<nSize;i++){
TimeData child = oList.get(i);
// get value using getters
}
You can try this ,Let say you have variables like
double dtime;
Timestamp tp;
And listofresults is coming from query results.
listofresults = results.getResultList();
If list is coming from query then put it in the loop this way in the condition of for loop
for(int i=0;i< listofresults.size() ;i=i+2)
{
dtime=(double) listofresults.get(i);
//cast because the value is of object type
tp=(TimeStamp) listofresults.get(i+1);
//cast because the value is of object type
//do something with these variables
}
I recommend creating a wrapper for it.
public class UpTimeDownTime {
MyTimeDataClass downtime;
MyTimeDataClass uptime;
public UpTimeDownTime(MyTimeDataClass downtime, MyTimeDataClass uptime){
this.downtime = downtime;
this.uptime = uptime;
}
public MyTimeDataClass getDowntime () {
return downtime;
}
public MyTimeDataClass getUptime () {
return uptime;
}
public static void main (String[] args) {
List<List<MyTimeDataClass>> List = ...;
List<UpTimeDownTime> uptimeDowntime = new ArrayList<UpTimeDownTime>();
for(List<MyTimeDataClass> timeList : List){
UpTimeDownTime u = new UpTimeDownTime(timeList.get(0), timeList.get(1));
uptimeDowntime.add(u);
}
}
}
I have an Arraylist of Records.
package com.demo.myproject;
public class Records
{
String countryName;
long numberOfDays;
public String getCountryName() {
return countryName;
}
public void setCountryName(String countryName) {
this.countryName = countryName;
}
public long getNumberOfDays() {
return numberOfDays;
}
public void setNumberOfDays(long numberOfDays) {
this.numberOfDays = numberOfDays;
}
Records(long days,String cName)
{
numberOfDays=days;
countryName=cName;
}
}
My Arraylist<Records> is containing the values
Singapore 12
Canada 3
United Sates 12
Singapore 21
I need to modify it such that my output is
Canada 3
Singapore 33
United States 12
Please help me with solution,approach.
You could store your Records in a Map, where the key would be the country.
When you receive a new Record, check if the country already is in the map, if it is, add the number of days, if not create it.
Map<String, Record> map = new HashMap<String, Record> ();
addRecord(map, someRecord);
private void addRecord(Map<String, Record> map, Record record) {
Record inMap = map.get(record.getCountryName());
if (inMap == null) {
inMap = record;
} else {
inMap.setNumberOfDays(inMap.getNumberOfDays() + record.getNumberOfDays());
}
map.put(record.getCountryName(), inMap);
}
Notes:
I have assumed that it is fine to modify the records - if not just create a new one using the sum of the days.
you can still get the collection of records by calling map.values(); and iterate over them
ArrayList is not very well suited for your use case. If you really need to stick to ArrayList, for evey new record, you would need to loop over the list, check if one of the records in the list has the same country as the new record, update that record if you find it, or add a new record if not.
public class RecordsMain {
static ArrayList<Records> al = new ArrayList<Records>();
static boolean flag = false;
public static void main(String[] args) {
Records rec1 = new Records(12,"Singapore");
Records rec2 = new Records(3,"Canada");
Records rec3 = new Records(12,"United States");
Records rec4 = new Records(21,"Singapore");
addToList(rec1);
addToList(rec2);
addToList(rec3);
addToList(rec4);
for (int i = 0; i < al.size(); i++) {
System.out.println(al.get(i).getCountryName() + " :: " + al.get(i).getNumberOfDays());
}
}
public static void addToList(Records records) {
for (int i = 0; i < al.size(); i++) {
if(al.get(i).getCountryName().equals(records.getCountryName())) {
al.get(i).setNumberOfDays(al.get(i).getNumberOfDays()+records.getNumberOfDays());
flag=true;
}
}
if (flag == false)
al.add(records);
}
}
Note:
The function addToList adds records and while adding itself checks whether the CountryNames are duplicate, if they are it adds the No of days and does not marks any new entry to the ArrayList.
I was not sure if you were looking for sorting of the List too, thus did not try that.
I suppose you create these records on your own. If you don't need any specific order of the elements you should use the HashMap and as assylias said - create country elements only when they doesn't exist. When you need to keep the order of elements (or sort them later by name etc) you can still use the ArrayList and "indexOf()" method to easily find them.
I dont know what exactly you want to do there but if you want to sort it with specific criteria then You could use comparable or comparator interfaces to sort your records using your criteria in ArrayList And use collections.sort() method to sort it.