This question already has answers here:
Is there a way to access an iteration-counter in Java's for-each loop?
(16 answers)
Closed 3 years ago.
here Is Code there any way to get Index of the object from the list by calling a method in the list.
for example something like this:
class A{
String a="";
String b="";
}
List<A> alist= new ArrayList();
for (A a : alist) {
a.getIndexInList();
}
Why not use indexOf? If I recall correctly it is a built-in function of list.
List<A> alist= new ArrayList<>();
for (A a : alist) {
int index = alist.indexOf(a);
}
Only the list can give you the index. Unless the object in the array knows it's in an array it can't give you it's index.
There is no builtin solution, you can use external counter:
List<A> alist= new ArrayList();
int counter = 0;
for (A a : alist) {
// logic
counter++;
}
You could also create a map with indices as keys, something like:
IntStream.range(0, alist.size()).mapToObj(Integer::valueOf)
.collect(Collectors.toMap(
Function.identity(),
alist::get
));
but alist needs to be effectively final.
Related
This question already has answers here:
How can I initialize an ArrayList with all zeroes in Java?
(5 answers)
Creating a list with repeating element
(5 answers)
Create an array with n copies of the same value/object?
(7 answers)
Closed 1 year ago.
Is there a way to fast initialize a new ArrayList object with X same objects?
Here is an example code:
private List<String> initStringArrayList(int size, String s) {
List<String> list = new ArrayList<>(size);
while (size-- > 0) {
list.add(s);
}
return list;
}
I want to have the same result, but much faster for large "size" values.
Of course, I could use this code:
private List<String> initStringArrayList(int size, String s) {
String[] array = new String[size];
Arrays.fill(array, s);
return new ArrayList<>(Arrays.asList(array));
}
But the constructor of ArrayList<>() would copy the full array instead of using it internal. That would not be acceptable.
Is there another way to do so? I need an ArrayList as result, not just a list. And it should be of any type, not just for strings.
Thank you for any answer!
Use Collections.nCopies, and copy it into an ArrayList:
private <T> List<T> initStringArrayList(int size, T s) {
return new ArrayList<>(Collections.nCopies(size, s));
}
This assumes that you really do want a mutable List at the end. If you can make do with an immutable list with the item size times, Collections.nCopies(size, s) by itself would work: it is memory-efficient, fast to allocate etc.
This question already has answers here:
How to lowercase every element of a collection efficiently?
(11 answers)
Closed 6 years ago.
I'm having trouble figuring out how to apply a math operation to each item of an ArrayList. The ArrayList will be user inputted so there's no telling how many items would be within it. Is there a method that might aid in doing this?
Use ListIterator -> https://docs.oracle.com/javase/7/docs/api/java
/util/ListIterator.html
Unlike plain Iterator, ListIterator will allow you to store newly computed value back to the list
ArrayList<Integer> source = ...
ListIterator<Integer> iter = source.listIterator();
while( iter.hasNext() )
{
Integer value = iter.next();
Integer newValue = Integer.valueOf( value.intValue() * 2 );
iter.set(newValue);
}
as #puhlen says, in java 8, use stream and lambda expression
List liste = new ArrayList<>();
liste.stream().forEach(o->{
//apply your math on o
});
stream provides you many other functionnalities to filter, order, collect... use it if you're on java8
or as #neil-locketz says in java before 8 use a foreach loop
List<type> liste = new ArrayList<>();
for(type o : liste){
//math on object o here
}
This question already has answers here:
Convert list to array in Java [duplicate]
(11 answers)
Closed 8 years ago.
I have a created a LinkedList with an Employee object stored in it. I need to write a method convertToArray that would make an array of Employees by taking it from the LinkedList.
Any ideas?
The easiest way to do this is to utilize LinkedList.toArray method
// create an array and copy the list to it
Employee[] array = list.toArray(new Employee[list.size()]);
However, if you are just learning and would like to do this iteratively. Think about how you would declare and get all of the items into an array.
First, what do you need to do?
1) Declare the array of Employee's
In order to do that, you to know how big to make the array since the size of an array cannot be changed after declaration. There is a method inherited from List called .size()
Employee[] array = new Employee[list.size()]
2) For each slot in the array, copy the corresponding element in the list
To do this, you need to utilize a for loop
for(int i = 0; i < array.length; i++) {
//access element from list, assign it to array[i]
}
public <T> T[] convert (List<T> list) {
if(list.size() == 0 ) {
return null;
}
T[] array = (T[])Array.newInstance(list.get(0).getClass(), list.size());
for (int i=0;i<list.size();i++) {
array[i] = list.get(i);
}
return array;
}
Employee[] arr = new Employee[list.size()];
int i = 0;
for(Employee e : list) {
arr[i] = e;
i++;
}
This question already has answers here:
How do I remove repeated elements from ArrayList?
(40 answers)
Closed 9 years ago.
I have a very lengthy ArrayList comprised of objects some of them however, are undoubtedly duplicates. What is the best way of finding and removing these duplicates. Note: I have written a boolean-returning compareObjects() method.
Example
List<Item> result = new ArrayList<Item>();
Set<String> titles = new HashSet<String>();
for( Item item : originalList ) {
if( titles.add( item.getTitle() )) {
result.add( item );
}
}
Reference
Set
Java Data Structures
You mentioned writing a compareObjects method. Actually, you should override the equals method to return true when two objects are equal.
Having said that, I would just return a new list that contains unique elements from the original:
ArrayList<T> original = ...
List<T> uniques = new ArrayList<T>();
for (T element : original) {
if (!uniques.contains(element)) {
uniques.add(element);
}
}
This only works if you override equals. See this question for more information.
Hashset will remove duplicates. Example:
Set< String > uniqueItems = new HashSet< String >();
uniqueItems.add("a");
uniqueItems.add("a");
uniqueItems.add("b");
uniqueItems.add("c");
The set "uniqueItems" will contain the following : a, b, c
This question already has answers here:
Is List<Dog> a subclass of List<Animal>? Why are Java generics not implicitly polymorphic?
(19 answers)
Closed 5 years ago.
In Java, why doesn't the following line of code work?
List<List<String>> myList = new ArrayList<ArrayList<String>>();
It works if I change it to
List<ArrayList<String>> myList = new ArrayList<ArrayList<String>>();
At first, I thought maybe you can't have lists of an interface, but I can create a List<Runnable> just fine.
Ideas?
Generic types are more pedantic.
List means List or any sub-type, but <List> means only List. If you want a sub-type you need to have <? extends List>
I suspect you can use
List<List<String>> myList = new ArrayList<List<String>>();
The reason you can't do this is that you can be using a reference to a reference and with an extra level of indirection you have to be careful.
// with one level of indirection its simple.
ArrayList alist = new ArrayList();
List list = aList; // all good
list = new LinkedList(); // alist is still good.
With generics you can have two level of indirection which can give you problems so they are more pedantic to avoid these issues.
// with two levels of indirection
List<ArrayList> alist = new ArrayList<ArrayList>();
List<List> list = (List) alist; // gives you a warning.
list.add(new LinkedList()); // adding a LinkedList into a list of ArrayList!!
System.out.println(alist.get(0)); // runtime error
prints
Exception in thread "main" java.lang.ClassCastException: java.util.LinkedList
cannot be cast to java.util.ArrayList
Lets start with this:
ArrayList<ArrayList<String>> myList = new ArrayList<ArrayList<String>>();
This is creating an ArrayList whose elements are ArrayLists.
Now suppose we could assign that to
List<List<String>> myList2 = myList.
Now, we should be able to do this:
myList2.add(new LinkedList<String>());
But that means we have added a LinkedList to a list whose elements are supposed to be ArrayLists. Ooops!!!
In reality, the assignment of myList to myList2 is not legal ... and that ensures that it is not possible to add the wrong kind of List<String> to the ArrayList<ArrayList<String>> object. (No Peter, it is not just pedantry :-) )
Only the top level collection can be declared as an implementing class, while the nested ones must remain interfaces until you actually create instances:
List<List<String>> rootList = new ArrayList<List<String>>();
and then when you create an element to go in, you make it an implementation:
List<String> nodeList = new ArrayList<String>();
rootList.add(nodeList);
Its comparing Type from left(declaration) side to Type from right(instantiation) side. In Left, your type is List<String> while in right, it's ArrayList<String>. If complaining about the difference.
Please update the right side(instatiation) as List i.e.
List<List<String>> myList = new ArrayList<List<String>>();
This should work fine.
I know this is an old question but I just wanted to share my idea.
Instead of making a List of Lists, I personally just make a List of Type[] (List<Type[]> listArray = new ArrayList<Type[]>();), I generate a separate List of just Type (List<Type> list = new ArrayList<Type>();), then .add(list.toArray()). This way, it's clearer and easier to read than the List of Lists syntax which is confusing.
For example, in a recent project where I had an input file where each line with only a "0" meant a new line in the original (it was an encryption algorithm):
String[] input = getInputContents(inFile);
List<String> currentBuffer = new ArrayList<String>();
List<String[]> buffers = new ArrayList<String[]>();
for(String line : input) {
if(line.equals("0")) {
buffers.add((String[])currentBuffer.toArray());
currentBuffer = new ArrayList<String>();
} else {
currentBuffer.add(line);
}
}
the list<list<string>> l1=new list<list<string>>(); is allowed if the list contains one more list inside the list.
public final class CPanelXMLBuilder extends PanelXMLBuilder {
public CPanelXMLBuilder(AuthenticatedUser pAuthenticatedUser, Map<String, Object> pSessionMap, Map<String, Object> pRequestMap, String pPanelTemplate) throws Exception {
super(pAuthenticatedUser, pSessionMap, pRequestMap, pPanelTemplate, null);
}
public Map<String, Object> buildXMLDocument(List<List<String>> pDetailsList) {
if (pDetailsList.size() == 1) {
List<String> pCustomerDetail = pDetailsList.get(0);
xmlDocument.getRootElement().getChild("E_SHOW1").setText(pCustomerDetail.get(0));
xmlDocument.getRootElement().getChild("E_SHOW2").setText(pCustomerDetail.get(1));
xmlDocument.getRootElement().getChild("E_SHOW3").setText(pCustomerDetail.get(2));
xmlDocument.getRootElement().getChild("E_SHOW4").setText(pCustomerDetail.get(3));
xmlDocument.getRootElement().getChild("E_SHOW5").setText(pCustomerDetail.get(4));
xmlDocument.getRootElement().getChild("ServerTimestamp").setText(pCustomerDetail.get(5).substring(0, 19));
} else {
xmlDocument.getRootElement().getChild("AlertType").setText("INFO");
xmlDocument.getRootElement().getChild("Alert").setText("There is no matching record.");
}
requestMap.put(RequestMapKeys.XML_DOCUMENT, xmlDocument);
return requestMap;
}
}