in java,how to iterate list of objects - java

i am having the list myEmpls
List myEmpls = new ArrayList();
In this list i have added used defined objects.
LogConf e = getLogs(el);
//add it to list
myEmpls.add(e);
Now how to iterate the list of objects and get the values from this objects.
How to do this?

You could just google this and you would find tons of solutions.. But here is the code:
for(LogConf element : myEmpls) {
System.out.println(element.getValue());
}
You should also get used to define the type of the elements in the list:
List<LogConf> myEmpls = new ArrayList<LogConf>();

I know its been some time since this post was made. You can also use the Iterator.
List myEmpls = new ArrayList();
Iterator itr = myEmpls.iterator();
while(itr.hasNext()) {
LogConf Logobj = (LogConf) itr.next();
System.out.println(Logobj.getterName());
}
Hope this helps someone.

Related

how to get substring items with in arraylist in java

I have arraylist of strings, I need to find the substrings among the items in same arraylist?
For example:
ArrayList<String> ar = new ArrayList();
ar.add("UserId"); //adding item to arraylist
ar.add("Directory");
ar.add("Username");
ar.add("PhoneNumber");
Here I want to find substring of items, basically I need output as UserId and Username from the list items. how can I do it can someone help me out.
you have two approaches:
ArrayList<String> ar = new ArrayList();
ar.add("UserId"); //adding item to arraylist
ar.add("Directory");
ar.add("Username");
ar.add("PhoneNumber");
// approach one using iteration
for (Iterator<String> it = ar.iterator(); it.hasNext(); ) {
String f = it.next();
if (f.equals("UserId"))
System.out.println("UserId found");
}
// approach two using a colletion which supports fetching element by key
Map<String,String> myMap=new HashMap<>();
for(String strg:ar){
myMap.put(str,str);
}
String result=myMap.get("UserId");
If you have repeating element (for example several "UserId" element), you can use collections that support bags (sets with duplicate elemets), for example guava mutiset

how to remove duplicate Element from Arraylist in java

{ "744101", "744101","744101", "744102",744102","744102","744102","744102","744103","744103"}
List<String> list2=new new ArrayList<String>(); //
Arrays.sort(iArr);
for(int k=0;k<iArr.length;k++) {
list2.add(String.valueOf(iArr[k]));
}
List li2 = new Array List(new HashSet(list2));
I'm unable to get result while trying to Sort Array list. Please correct me.
The TreeSet both sorts the elements and removes the duplicates.
String[] array = { "744101", "744101","744101", "744102","744102","744102","744102","744102","744103","744103"};
List<String> list = new ArrayList<>(new TreeSet<>(Arrays.asList(array)));
list.forEach((element)->{
System.out.println(element);
});
Try this:
List<String> list = new ArrayList<>();
Set<String> set = new HashSet<>();
hash.addAll(list);
list.clear();
list.addAll(hash);
And than sort list if you want.
As Eran mentioned, you current implementation "shuffles" the list due to HashSet implementation being used, as this Set implementation doesn't retain the order. Try using LinkedHashSet instead. As mentioned in javadoc it avoids overheads related to TreeSet.
Code would be something like this
String[] arrayToProcess = { "744101", "744101","744101", "744102","744102","744102","744102","744102","744103","744103"};
//creates array and sorts the list
List<String> sortedList = Arrays.asList(arrayToProcess);
Collections.sort(sortedList);
//removes duplicates the list, while retaining order of sorted list
Set<String> uniqueNumbers = new LinkedHashSet<String>();
uniqueNumbers.addAll(sortedList);
Note the implementation of Set being used is LinkedHashSet. Also this snippet makes two copies of the array so if array size is huge, I wouldn't suggest using it.
I would suggest you look up the implementations of collections in java. Because each of them has their own strengths and weaknesses:

Removing item from list while iterating

While iterating through a list, an item can possibly be removed.
private void removeMethod(Object remObj){
Iterator<?> it = list.iterator();
while (it.hasNext()) {
Object curObj= it.next();
if (curObj == remObj) {
it.remove();
break;
}
}
}
The problem for me occurs when the above code can take place in another loop, which is actively iterating the original list.
private void performChecks(){
for(Object obj : list){
//perform series of checks, which could result in removeMethod
//being called on a different object in the list, not the current one
}
}
How can I remove an unknown object from a list while traversing it?
Example
I have a list of listener objects. While notifying the listeners of an event, other listeners may no longer be needed.
If I understand your problem correctly, followings would be the possible solutions(might not be most effective but i think is worth a shot):
Under performChecks() use for(Object obj : list.toArray())
Advantage: every time the list is "refreshed" to array it will reflect the changes.
Therefore, if the item is removed from the list in the separate loop
Your question is a bit confusing so I'll answer what I think I understand; your question comes to this: how to remove an item from a list while the list is iterated concurrently and items are being removed OR how to avoid ConcurrentModificationException.
First, the problem in your code is that you remove the item with your iterator and not by the list. Second, if you're using concurrency, use the CopyOnWriteArrayList and remove the item with
list.remove()
to provide a good example for the scenario, check this
so this is not good:
List<String> myList = new ArrayList<String>();
myList.add("1");
myList.add("2");
myList.add("3");
myList.add("4");
myList.add("5");
Iterator<String> it = myList.iterator();
while(it.hasNext()){
String value = it.next();
System.out.println("List Value:"+value);
if(value.equals("3")) myList.remove(value);
}
and this is good:
List<String> myList = new CopyOnWriteArrayList<String>();
myList.add("1");
myList.add("2");
myList.add("3");
myList.add("4");
myList.add("5");
Iterator<String> it = myList.iterator();
while(it.hasNext()){
String value = it.next();
System.out.println("List Value:"+value);
if(value.equals("3")){
myList.remove("4");
myList.add("6");
myList.add("7");
}
}
System.out.println("List Size:"+myList.size());

Filtering list values, should I create a new list or delete values from the original one

Say I have a list that contains either single values, or value ranges. Now if I add a new value or a range to this list, it might overlap with none to multiple of the current values/ranges. All these overlapping objects should be combined to create a new instance, that should be added to the list, meanwhile the objects that got included in the new instance need to be deleted from the original list.
So my question is, should I really delete those objects from the list or create a new list on every iteration. That is, put to code:
Solution 1
for (Range newObj : newItems){
Iterator it = oList.iterator();
while (it.hasNext()){
Range o = it.next();
if (canCombine(newObj, o)){
newObj = combine(newObj, o);
it.remove();
}
}
oList.add(newObj);
}
Solution 2
for (Range newObj : newItems){
List newList = new ArrayList();
for (Range o : oList){
if (canCombine(newObj, o)){
new = combine(newObj, o);
} else {
newList.add(o);
}
}
newList.add(newObj);
oList = newList;
}
Maybe another solution is even better. If so, kindly let me know.
I think you can avoid creating newList every time you iterate your newItems or you can avoid the creation of new list at all.
for (Object newObj : newItems){
for(int i=0;i<oList.size();i++){
if (canCombine(newObj, oList.get(i))){
newObj = combine(newObj, oList.get(i));
oList.remove(i);
}
}
oList.add(newObj);
}

Create List<T> instance from Iterator<T>

Anyone know if there is a standard way to create a List from an Iterator instance?
I tend towards Guava's Lists.newArrayList(Iterator) because I generally have Guava as a dependency, and it already exists.
Use the Iterator to get every element and add it to a List.
List<String> list = new LinkedList<String>();
while(iter.hasNext()) { // iter is of type Iterator<String>
list.add(iter.next());
}
I had this need, and as a user of Apache Commons, this is what I did:
IteratorUtils.toList(iterator);
Javadoc here: https://commons.apache.org/proper/commons-collections/javadocs/api-3.2.2/org/apache/commons/collections/IteratorUtils.html#toList(java.util.Iterator)
In Java 8 you can use these ways (while verbose enough):
Iterator<String> iterator = ...;
List<String> list = StreamSupport.stream(Spliterators.spliteratorUnknownSize(iterator, Spliterator.ORDERED), false)
.collect(Collectors.toList());
or
Iterator<String> iterator = ...;
List<String> list = new ArrayList<>(); // or LinkedList() if more relevant (adding being faster for LinkedList)
iterator.forEachRemaining(list::add);
try something like the following:
public T List<T> listFromIterator(Iterator<T> iterator) {
List<T> result = new LinkedList<T>();
while(iterator.hasNext()) {
result.add(iterator.next());
}
}
One thing to note is that if the iterator is not at the beginning of your structure, you have no way of retrieving previous elements.
If you have the collection that the iterator is from, you can create a list by using a constructor that takes a collection. ex: the LinkedList constructor:
LinkedList(Collection<? extends E> c)
This is the way that I convert from List to Iterator and vice versa.
ArrayList arrayList = new ArrayList();
// add elements to the array list
arrayList.add("C");
arrayList.add("A");
arrayList.add("E");
arrayList.add("B");
arrayList.add("D");
arrayList.add("F");
// use iterator to display contents of arrayList
System.out.print("Original contents of arrayList: ");
Iterator iterator = arrayList.iterator();
ArrayList arrayList2 = new ArrayList();
while(iterator.hasNext()) {
Object element = iterator.next();
arrayList2.add(element);
System.out.print(element + " ");
}

Categories