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;
}
Related
How could I go about detecting (returning true/false) whether an ArrayList contains more than one of the same element in Java?
Many thanks,
Terry
Edit
Forgot to mention that I am not looking to compare "Blocks" with each other but their integer values. Each "block" has an int and this is what makes them different.
I find the int of a particular Block by calling a method named "getNum" (e.g. table1[0][2].getNum();
Simplest: dump the whole collection into a Set (using the Set(Collection) constructor or Set.addAll), then see if the Set has the same size as the ArrayList.
List<Integer> list = ...;
Set<Integer> set = new HashSet<Integer>(list);
if(set.size() < list.size()){
/* There are duplicates */
}
Update: If I'm understanding your question correctly, you have a 2d array of Block, as in
Block table[][];
and you want to detect if any row of them has duplicates?
In that case, I could do the following, assuming that Block implements "equals" and "hashCode" correctly:
for (Block[] row : table) {
Set set = new HashSet<Block>();
for (Block cell : row) {
set.add(cell);
}
if (set.size() < 6) { //has duplicate
}
}
I'm not 100% sure of that for syntax, so it might be safer to write it as
for (int i = 0; i < 6; i++) {
Set set = new HashSet<Block>();
for (int j = 0; j < 6; j++)
set.add(table[i][j]);
...
Set.add returns a boolean false if the item being added is already in the set, so you could even short circuit and bale out on any add that returns false if all you want to know is whether there are any duplicates.
Improved code, using return value of Set#add instead of comparing the size of list and set.
public static <T> boolean hasDuplicate(Iterable<T> all) {
Set<T> set = new HashSet<T>();
// Set#add returns false if the set does not change, which
// indicates that a duplicate element has been added.
for (T each: all) if (!set.add(each)) return true;
return false;
}
With Java 8+ you can use Stream API:
boolean areAllDistinct(List<Block> blocksList) {
return blocksList.stream().map(Block::getNum).distinct().count() == blockList.size();
}
If you are looking to avoid having duplicates at all, then you should just cut out the middle process of detecting duplicates and use a Set.
Improved code to return the duplicate elements
Can find duplicates in a Collection
return the set of duplicates
Unique Elements can be obtained from the Set
public static <T> List getDuplicate(Collection<T> list) {
final List<T> duplicatedObjects = new ArrayList<T>();
Set<T> set = new HashSet<T>() {
#Override
public boolean add(T e) {
if (contains(e)) {
duplicatedObjects.add(e);
}
return super.add(e);
}
};
for (T t : list) {
set.add(t);
}
return duplicatedObjects;
}
public static <T> boolean hasDuplicate(Collection<T> list) {
if (getDuplicate(list).isEmpty())
return false;
return true;
}
I needed to do a similar operation for a Stream, but couldn't find a good example. Here's what I came up with.
public static <T> boolean areUnique(final Stream<T> stream) {
final Set<T> seen = new HashSet<>();
return stream.allMatch(seen::add);
}
This has the advantage of short-circuiting when duplicates are found early rather than having to process the whole stream and isn't much more complicated than just putting everything in a Set and checking the size. So this case would roughly be:
List<T> list = ...
boolean allDistinct = areUnique(list.stream());
If your elements are somehow Comparable (the fact that the order has any real meaning is indifferent -- it just needs to be consistent with your definition of equality), the fastest duplicate removal solution is going to sort the list ( 0(n log(n)) ) then to do a single pass and look for repeated elements (that is, equal elements that follow each other) (this is O(n)).
The overall complexity is going to be O(n log(n)), which is roughly the same as what you would get with a Set (n times long(n)), but with a much smaller constant. This is because the constant in sort/dedup results from the cost of comparing elements, whereas the cost from the set is most likely to result from a hash computation, plus one (possibly several) hash comparisons. If you are using a hash-based Set implementation, that is, because a Tree based is going to give you a O( n logĀ²(n) ), which is even worse.
As I understand it, however, you do not need to remove duplicates, but merely test for their existence. So you should hand-code a merge or heap sort algorithm on your array, that simply exits returning true (i.e. "there is a dup") if your comparator returns 0, and otherwise completes the sort, and traverse the sorted array testing for repeats. In a merge or heap sort, indeed, when the sort is completed, you will have compared every duplicate pair unless both elements were already in their final positions (which is unlikely). Thus, a tweaked sort algorithm should yield a huge performance improvement (I would have to prove that, but I guess the tweaked algorithm should be in the O(log(n)) on uniformly random data)
If you want the set of duplicate values:
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class FindDuplicateInArrayList {
public static void main(String[] args) {
Set<String> uniqueSet = new HashSet<String>();
List<String> dupesList = new ArrayList<String>();
for (String a : args) {
if (uniqueSet.contains(a))
dupesList.add(a);
else
uniqueSet.add(a);
}
System.out.println(uniqueSet.size() + " distinct words: " + uniqueSet);
System.out.println(dupesList.size() + " dupesList words: " + dupesList);
}
}
And probably also think about trimming values or using lowercase ... depending on your case.
Simply put:
1) make sure all items are comparable
2) sort the array
2) iterate over the array and find duplicates
To know the Duplicates in a List use the following code:It will give you the set which contains duplicates.
public Set<?> findDuplicatesInList(List<?> beanList) {
System.out.println("findDuplicatesInList::"+beanList);
Set<Object> duplicateRowSet=null;
duplicateRowSet=new LinkedHashSet<Object>();
for(int i=0;i<beanList.size();i++){
Object superString=beanList.get(i);
System.out.println("findDuplicatesInList::superString::"+superString);
for(int j=0;j<beanList.size();j++){
if(i!=j){
Object subString=beanList.get(j);
System.out.println("findDuplicatesInList::subString::"+subString);
if(superString.equals(subString)){
duplicateRowSet.add(beanList.get(j));
}
}
}
}
System.out.println("findDuplicatesInList::duplicationSet::"+duplicateRowSet);
return duplicateRowSet;
}
best way to handle this issue is to use a HashSet :
ArrayList<String> listGroupCode = new ArrayList<>();
listGroupCode.add("A");
listGroupCode.add("A");
listGroupCode.add("B");
listGroupCode.add("C");
HashSet<String> set = new HashSet<>(listGroupCode);
ArrayList<String> result = new ArrayList<>(set);
Just print result arraylist and see the result without duplicates :)
This answer is wrriten in Kotlin, but can easily be translated to Java.
If your arraylist's size is within a fixed small range, then this is a great solution.
var duplicateDetected = false
if(arrList.size > 1){
for(i in 0 until arrList.size){
for(j in 0 until arrList.size){
if(i != j && arrList.get(i) == arrList.get(j)){
duplicateDetected = true
}
}
}
}
private boolean isDuplicate() {
for (int i = 0; i < arrayList.size(); i++) {
for (int j = i + 1; j < arrayList.size(); j++) {
if (arrayList.get(i).getName().trim().equalsIgnoreCase(arrayList.get(j).getName().trim())) {
return true;
}
}
}
return false;
}
String tempVal = null;
for (int i = 0; i < l.size(); i++) {
tempVal = l.get(i); //take the ith object out of list
while (l.contains(tempVal)) {
l.remove(tempVal); //remove all matching entries
}
l.add(tempVal); //at last add one entry
}
Note: this will have major performance hit though as items are removed from start of the list.
To address this, we have two options. 1) iterate in reverse order and remove elements. 2) Use LinkedList instead of ArrayList. Due to biased questions asked in interviews to remove duplicates from List without using any other collection, above example is the answer. In real world though, if I have to achieve this, I will put elements from List to Set, simple!
/**
* Method to detect presence of duplicates in a generic list.
* Depends on the equals method of the concrete type. make sure to override it as required.
*/
public static <T> boolean hasDuplicates(List<T> list){
int count = list.size();
T t1,t2;
for(int i=0;i<count;i++){
t1 = list.get(i);
for(int j=i+1;j<count;j++){
t2 = list.get(j);
if(t2.equals(t1)){
return true;
}
}
}
return false;
}
An example of a concrete class that has overridden equals() :
public class Reminder{
private long id;
private int hour;
private int minute;
public Reminder(long id, int hour, int minute){
this.id = id;
this.hour = hour;
this.minute = minute;
}
#Override
public boolean equals(Object other){
if(other == null) return false;
if(this.getClass() != other.getClass()) return false;
Reminder otherReminder = (Reminder) other;
if(this.hour != otherReminder.hour) return false;
if(this.minute != otherReminder.minute) return false;
return true;
}
}
ArrayList<String> withDuplicates = new ArrayList<>();
withDuplicates.add("1");
withDuplicates.add("2");
withDuplicates.add("1");
withDuplicates.add("3");
HashSet<String> set = new HashSet<>(withDuplicates);
ArrayList<String> withoutDupicates = new ArrayList<>(set);
ArrayList<String> duplicates = new ArrayList<String>();
Iterator<String> dupIter = withDuplicates.iterator();
while(dupIter.hasNext())
{
String dupWord = dupIter.next();
if(withDuplicates.contains(dupWord))
{
duplicates.add(dupWord);
}else{
withoutDupicates.add(dupWord);
}
}
System.out.println(duplicates);
System.out.println(withoutDupicates);
A simple solution for learners.
//Method to find the duplicates.
public static List<Integer> findDublicate(List<Integer> numList){
List<Integer> dupLst = new ArrayList<Integer>();
//Compare one number against all the other number except the self.
for(int i =0;i<numList.size();i++) {
for(int j=0 ; j<numList.size();j++) {
if(i!=j && numList.get(i)==numList.get(j)) {
boolean isNumExist = false;
//The below for loop is used for avoid the duplicate again in the result list
for(Integer aNum: dupLst) {
if(aNum==numList.get(i)) {
isNumExist = true;
break;
}
}
if(!isNumExist) {
dupLst.add(numList.get(i));
}
}
}
}
return dupLst;
}
I have two lists containing the same type of objects. Each object has an int, a string and some other stuff where the int is its index.
Here is the object that both lists are holding:
public class ListElement
{
private int index;
private String data;
private String some;
private String other;
private String stuff;
// gets, sets...
}
What i want is to take List A's index and "some other stuff" and replace its string "data" with the one from List B. The one it takes from List B should match the index of List A. I hope this is understandable.
EDIT: It should be noted that the index int inside the object has nothing to do with the actual position of the object in the list. Its for other porpuses
UPDATE: You mentioned that the index field of your ListElement has no relationship with its actual place in its containing List.
You just happen to have a field with a random name that you want to compare both list on (join on). This solution uses nested loops to compare every element in one list with every element in the other list.
for (int iA = 0; iA < listA.size(); iA++) //iterate over listA
{
ListElement currentElement = listA.get(iA);
for (int iB = 0; iB < listB.size(); iB++) //iterate over listB
{
ListElement other = listB.get(iB);
if (other.index == currentElement.index) //compare the elements
{
//do stuff
currentElement.setData(other.getData());
break; //if only want first match
}
}
}
Assuming your both list have the same number of elements, you could do something like:
ListElement sourceElement, destElement;
for (int i =0; i<list1.size(); i++) {
sourceElement = list1.get(0);
destElement = list2.get(0);
sourceElement.setData(destElement.getData());
...
}
The first idea is probably not the brightest but I'll come to that later.
For (ListElement e : ListA) {
For (ListElement le : ListB) {
if (e.getIndex() = le.getIndex()) {
e.setData(le.getData());
}
}
}
So this is my first shot for what you wrote, but it's probably not the easiest way. To make it simpler and faster you could implement the interface Comparable and use sort, i this case you access the List elements by the index in ListElement (assuming you assure the indices are complete from 1..n).
My favored solution would be to use some kind of maps to store the index as key, and the ListElement as value, then it's just MapA.get(i).setData(MapB.get(i).getData()) This is fool-prove, as long as for every item in MapA there is an according item in MapB with the same index.
If you want to match on the index field on the ListItem object, try this:
for (ListItem listItemA : listA) {
for (ListItem listItemB : listB) {
if (listItemB.getIndex() == listItemA.getIndex()) {
listItemA.setData(listItemB.getData());
}
}
}
If you're interested in matching based on index within the List objects, try
for (int i = 0; i < listA.size(); i++) {
listA.get(i).setData(listB.get(i).getData());
}
Hi community I have a question, I happen to have an array of objects loaded on startup, through that generate array another array of integers that contains your code, it appears that array of integers'm removing their values, what I want is to compare the list of integer array currently have with the array of objects, and remove all code object that whole array mentioned is found.
My code java:
private List<ValidColumnKey> columnCustomer;
private int[] selectedCustomer;
public void init(){
this.setColumnCustomer(new ArrayList<ValidColumnKey>());
this.getColumnCustomer().add(new ValidColumnKey(1, "Codigo", "code"));
this.getColumnCustomer().add(new ValidColumnKey(2, "Nombre", "name"));
this.getColumnCustomer().add(new ValidColumnKey(3, "Nombre Comercial", "comercialName"));
this.getColumnCustomer().add(new ValidColumnKey(4, "Estado", "isActive"));
this.setSelectedCustomer(new int [this.getColumnCustomer().size()]);
int i = 0;
for(ValidColumnKey column : this.getColumnCustomer()){
this.getSelectedCustomer()[i] = column.getCodigo();
i++;
}
}
I mean I would have my array of integers with codes removed, like this:
selectedCustomer = [1, 2, 3];
What I wanted was to remove from the list of objects that do not have codes in the array of integers, but it is not my code:
List<ValidColumnKey> auxRemoColumnKeys = new ArrayList<ValidColumnKey>();
for(ValidColumnKey column : this.getColumnCustomer()){
for(Integer codigo : this.getSelectedCustomer()){
if (column.getCodigo() != codigo) {
auxRemoColumnKeys.add(column);
break;
}
}
}
this.getColumnCustomer().remove(auxRemoColumnKeys);
I could guide the solution.
this.getColumnCustomer().remove(auxRemoColumnKeys);
This statement assumes you have a valid equals method for your class ValidColumnKey, which I suspect is probably not the case.
What you want to do is iterate with a Iterator. Some sample code could be like
Set<Integer> toRemoveCodes = new HashSet<Integer>(Arrays.asList(1, 2, 3));
for (Iterator<ValidColumnKey> it = this.getColumnCustomer().iterator(); it.hasNext(); ) {
ValidColumnKey curColumnKey = it.next();
Integer code = curColumnKey.codigo();
if (toRemoveCodes.contains(code)) {
it.remove();
}
}
There are multiple reasons your current attempt is failing. The first is that this line:
if (column.getCodigo() != codigo) {
Is testing for object equivalence between Integers, not value equavalence between ints. If you want to compare Integers, you have to use the equals method:
if (!column.getCodigo().equals(codigo)) {
However, if getCodigo returns an int and getSelectedCustomer returns an int[] then this line should be changed instead:
for(int codigo : this.getSelectedCustomer()){
Because you didn't need to use Integer in the first place.
Secondly, this line attempts to remove auxRemoColumnKeys itself so you probably mean removeAll:
this.getColumnCustomer().remove(auxRemoColumnKeys);
Lastly, your logic is generally flawed. It basically says "for each element in getColumnCustomer, if getCodigo is not equal to all of getSelectedCustomer remove it". I don't think that's what you've intended.
This is a modified loop that uses the same "add to a list and remove the list items" procedure but the logic will work:
List<ValidColumnKey> auxRemoColumnKeys = new ArrayList<ValidColumnKey>();
int[] selected = this.getSelectedCustomer();
for (ValidColumnKey column : this.getColumnCustomer()) {
int i = 0;
for ( ; i < selected.length; i++) {
/* note: if getCodigo returns an Integer change this check to
* "if (column.getCodigo().equals(selected[i])) {"
*/
if (column.getCodigo() == selected[i]) {
break;
}
}
/* this says "if the search loop did not break early" */
if (i == selected.length) {
auxRemoColumnKeys.add(column);
}
}
this.getColumnCustomer().removeAll(auxRemoColumnKeys);
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);
}
}
}
considering there is a structure as described in http://prohost.lt/stack/q.png
In the main arrayList we have n elements(sub arrayLists) (as for image we can consider n=3).
How to make a dynamic loop thru all sub arrayLists so as to get:
sarraylist1.get(0), sarrayList2.get(0), .. sarraylistN.get(0)
In case n=3 it would be
for(sarraylist1){
for( sarraylist2){
for(sarraylist3){
element from every list
}
}
}
Maybe I misunderstood what you were asking, but would something as simple as this not work?
List<List> lists = new ArrayList<List>();
for(List l : lists){
for(List subl: l)
Object o = subl.get(0);
}
Based on your scheme of the image, you can also do it with the "for while loop":
for (int mainArrayElements = 0; mainArrayElements < listOfLists.size(); mainArrayElements++) {
List arraysInMain = ((List)listOfLists.get(mainArrayElements));
for (int subArrayElements = 0; subArrayElements < arraysInMain.size(); subArrayElements++) {
List deepArray = ((List)listOfLists.get(subArrayElements));
for (int innerArrayElements = 0; innerArrayElements < deepArray.size() ; innerArrayElements++) {
System.out.println(deepArray.get(innerArrayElements));
}
}
}
But as mentioned before, recursion would be a really great combo to knock out the problem :).
Best regards.
If I understood correctly, you have one List containing n Lists for which you want to get the first, second and so on, element of each list. This code does that.
for (int i = 0; i < highestSizeOfChildrenList; i++) {
List<Object> lstOfItemInChild = new Arraylist<Object>();
for (List childList : mainList) {
if (i < childList.size()) {
lstOfItemInChild.add(childList.get(i));
}
}
// lstOfItemInChild now contains all the element i of the sub arrays
}
You will need to know the size of the biggest subList to get all the elements of that list, that is what highestSizeOfChildrenList represents.
After watching your comment I suggest you to use recursive approach to solve your problem.
public void recursiveCall(ArrayList list)
{
for ( Object obj : list)
{
if (obj instanceOf ArrayList)
{
recursiveCall((ArrayList)obj);
}
else
{
System.out.print(obj);
}
}
}