How to access list of ArrayList elements - java

I have List of ArrayList Elements, see below.
List<List<String>> x = new ArrayList<List<String>>();
it contains some array list elements.
eg.
x.get(0)->[1,2,3,4],
x.get(1)->([5,6,7,8],
x.get(2)->[9,10,11,12],
x.get(3)->[13,14,15,16]
i want to access element 3 from x.get(0) or element 7 from x.get(1) how to call that??

Each element of your list is a list and has the same interface that provides List<T> methods, e.g.
T get(int index)
boolean isEmpty()
void add(T element)
etc.
You can access element from the inner list by index
List<List<String>> x = new ArrayList<List<String>>();
// ... some data initialised
String element_0_3 = x.get(0).get(3);
Be aware that each List<String> element needs to have been created before accessing it. For instance, in order to add a new String at the [0,0] coordinates:
List<List<String>> x = new ArrayList<List<String>>();
List<String> x0 = new ArrayList<>();
x0.add("foo"); // add "foo" as the first string element
x.add(x0); // add x0 as the first List<String> element
You can also read values with an enhanced for loop, without using the indexes:
List<List<String>> x = new ArrayList<List<String>>();
//...
for (List<String> ls : x) { // iteration on the x list
for (String s : ls) { // iteration on each intern list
System.out.println(s);
}

You can follow like...
List<List<String>> x = new ArrayList<List<String>>();
List<String> subX = x.get(7);
if(null != subX && subX.size() != 0) {
String element = subX.get(0);
}

//To directly access any list member using for loop instead of foreach loop
List<List<Integer>> list = new ArrayList<List<Integer>>();
for(int i=0;i<list.size();i++){
for(int j=0;j<list.get(i).size();j++){
do_something_on(list.get(i).get(j);
}
}

Related

How could i transfer duplicate items in other ArrayList?

I have an array list
ArrayList<String> list=new ArrayList<String>();
list.add("Apple");
list.add("Ball");
list.add("Ball");
list.add("Cat");
list.add("Cat");
list.add("dog");
and I want to transfer duplicate strings to other ArrayList.
I mean 2nd array list should only contain Ball and Cat not Apple and dog.
Any kind of help is appreciated.
You can do this:
List<String> duplicates = new ArrayList<String>();
for(String str: list) {
if(Collections.frequency(list, str) > 1) {
duplicates.add(str);
}
}
duplicates will contain your duplicates
Try this:
// Custom list to ensure that one duplicate gets added to a list at most as
// opposed to n-1 instances (only two instances of a value in this list would
// be deceiving).
List<String> list = new ArrayList<>();
list.add("Apple");
list.add("Ball");
list.add("Ball");
list.add("Ball");
list.add("Ball");
list.add("Cat");
list.add("Cat");
list.add("Cat");
list.add("dog");
list.add("dog");
Set<String> set = new HashSet<>();
Set<String> setOfDuplicates = new HashSet<>();
for (String s : list) {
if (!set.add(s)) { // Remember that sets do not accept duplicates
setOfDuplicates.add(s);
}
}
List<String> listOfDuplicates = new ArrayList<>(setOfDuplicates);
You can use a Set as a way to help determine the duplicated elements then simply return an ArrayList of those elements.
public static ArrayList<String> retainDuplicates(ArrayList<String> inputList){
Set<String> tempSet = new HashSet<>();
ArrayList<String> duplicateList = new ArrayList<>();
for (String elem : inputList) {
if(!tempSet.add(elem)) duplicateList.add(elem);
}
return duplicateList.stream().distinct().collect(Collectors.toCollection(ArrayList::new));
}
call the method like so:
ArrayList<String> resultList = retainDuplicates(list);
note that I've used distinct() to remove any elements that occur more than once within the duplicateList. However, if you want to keep the duplicates regardless of theirs occurrences within the duplicateList then just perform return duplicateList; rather than return duplicateList.stream().distinct().collect(Collectors.toCollection(ArrayList::new));.
since you said your duplicates will all be next to each other, you can itterate through the list in pairs, and if the pair's elements match, there is a duplicate
here would be the general pseudo code for it
int first = 0
int second = 1
for (arraySize)
if (array[first] == array[second])
//there is a match here
newArray.add(array[first])
first += 1
second += 1
Note that this does not check the bounds of the array, which should be easy to implement yourself
now as for the second list not having duplicate items, you can simply store a variable with the last transfered item, and if the new found duplicate is the same, dont transfer it again
ArrayList<String> list=new ArrayList<String>();
list.add("Apple");
list.add("Ball");
list.add("Ball");
list.add("Cat");
list.add("Cat");
list.add("dog");
List<String> duplicateList= new ArrayList<String>();
for(String str: list) {
if(Collections.frequency(list, str) > 1) {
duplicateList.add(str);
}
}
System.out.println(duplicateList.toString());
//Here you will get duplicate String from the original list.

How To Compare An Element of Array With Element of another array in a ArrayList?

I have an array and i want to compare the first element of this array with every element of another array in an Arraylist?
The purpose of doing this is to check whether or not the first element of the array exist in the another array of an Arraylist.
is this possible?
if yes, how?
List<List<String>> arrayst = new ArrayList<List<String>>();
List<List<String>> arrayqu = new ArrayList<List<String>>();
List<List<String>> arrayya = new ArrayList<List<String>>();
List<String> items = Arrays.asList(line.split(":",-1));
// i want to compare 1st element of items with 3 of the list above.
Create a different class and try something like this -
public class StackOverflow {
public void compare(List<String> items, List<List<String>> list){
String itemToBeCompared=items.get(0);
for(List<String> l:list){
if(l.contains(itemToBeCompared)){
System.out.println("Its Present");
}
else{
System.out.println("Not Present");
}
}
}
}
Then in the main method do something like this -
List<List<String>> arrayst = new ArrayList<List<String>>();
List<List<String>> arrayqu = new ArrayList<List<String>>();
List<List<String>> arrayya = new ArrayList<List<String>>();
List<String> items = Arrays.asList(line.split(":",-1));
StackOverflow st=new StackOverflow();
st.compare(items,arrayst);
st.compare(items,arrayqu);
st.compare(items,arrayya);
Hope this helps! Please let me know if this works for you.

java 2d arraylist edit inside loop

I have a 2d ArrayList which stores objects, i want to check if a certain object exists in any of of the rows, and if not add a new row, and search that object in future checks. eg.
ArrayList<List<Object>> list = new ArrayList<>();
for(List<Object> o : list) {
if(!o.contains(object){
ArrayList<Object> newList = new ArrayList<>();
newList.add(object);
list.add(newList);
}
}
This gives me a 'ConcurrentModificationException' but I can't find another way to do it.
Thanks in advance.
list.add(newList); this line should be outside your for loop. You are trying to modify your list while iterating on it. Just keep adding elements to newList in the for loop. Add the line list.add(newList); after the for loop.
You cannot change a List while you are iterating over its items.
What you can do is:
ArrayList<List<Object>> list = new ArrayList<>(); // in practice this would not be an empty list, but it would, as in your example, contain all items
ArrayList<List<Object>> newRows = new ArrayList<>();
for(List<Object> o : list) {
if(!o.contains(object){
ArrayList<Object> newList = new ArrayList<>();
newList.add(object);
newRows.add(newList);
}
}
list.addAll(newRows);
You have to replace:
for(List o : list) {
with:
for(int i = 0; i < list.size(); i++) {
List o = list.get(i);
Just be careful when you do this to handle how you modify the list. In this case there should be no problem.

Insert data in an array list java

I have two lists one is feature and has a placement number based on which i insert data in sorted list e.g if placement number is 5 data will be added in 5th position .i want to add data at 5th postion and to move data which was at 5th position to next index but in my case it just replace data at 5th position not move current data to next position
for (int i = 0; i < featuredList.size(); i++) {
int n = featuredList.get(i).getPlacementNumber().intValue();
if (n < sortedList.size()) {
sortedList.add(n, featuredList.get(i));
} else {
sortedList.add(featuredList.get(i));
}
}
You should use ArrayList, from add(int index, E element)
Inserts the specified element at the specified position in this list. Shifts the element currently at that position (if any) and any subsequent elements to the right (adds one to their indices).
Make your sortedList as ArrayList:
List<YourType> sortedList= new ArrayList<YourType>();
See the example http://ideone.com/L6hpsf
String s1 = "s1";
String s2 = "s2";
String s3 = "s3";
List<String> list = new ArrayList<String>();
list.add(s1);
list.add(s3);
list.add(1, s2);
System.out.println(list);
Output: [s1, s2, s3]
Try to use LinkedList to insertion or deletion between list for better performance then ArrayList :
private LinkedList<String> linkedList = new LinkedList<String>();
linkedList.add("1");
linkedList.add("2");
linkedList.add("3");
linkedList.add("4");
linkedList.add("5");
// insertion at 3 position
linkedList.add(2,"6");
Another example which may give you some clue and even easy to run :)
import java.util.ArrayList;
public class Alisttest {
public static void main(String[] args) {
ArrayList a = new ArrayList();
a.add("1");
a.add("2");
a.add("3");
a.add("4");
System.out.println("a=> "+a.get(2));
a.add(2, "Pankaj");
System.out.println("a=> "+a.get(2));
System.out.println();
System.out.println("a=> "+a);
}
}

How to operate on an ArrayList of ArrayList in Java?

I'm facing a problem when operating on an ArrayList of ArrayList in Java. I have this thing in my code-
ArrayList<ArrayList<Integer>> L1 = new ArrayList<ArrayList<Integer>>();
Problem is, I have no idea as to how I should operate on this (addition, removal, traversal etc.). I wish to create an adjacency list (for implementing simple, undirected graphs), and my instructor suggests that I should create an ArrayList of ArrayList. I know I can do the following to add new element-
L1.add(//Something I want to add);
But this throws up an error in the current case for obvious reasons.
An ArrayList of an ArrayList, just think that the outer object is an ArrayList and you are done.
ArrayList<ArrayList<Integer>> list2d = new ArrayList<ArrayList<Integer>>();
// add an element to the list
list2d.add(new ArrayList<Integer>());
// retrieve a list
ArrayList<Integer> list1d = list2d.get(0);
// add an integer
list2d.get(0).add(123);
By the way, an adjacency list is just a list of edges, there's no need to store them for each vertex, especially if the graph is undirected. A list of Edge would be enough:
class Edge {
Vertex v1, v2;
}
ArrayList<Edge> adjacencyList;
If you want to store them on a per vertex basis then you could avoid using a list of lists by encapsulating the edges inside the vertex class itself but this will require twice the edges:
class Vertex {
int value;
ArrayList<Vertex> adjacency;
}
but which one is best depends on what kind of operation you need to perform on the graph. For a small graph there is no practical difference.
Another possible implementation, if you just need to know if two vertex are connected:
class Edge {
public final int v1, v2;
public boolean equals(Object o) { return o != null && o instanceof Edge && o.hashCode() == hashCode(); }
public int hashCode() { return v1 ^ v2; } // simple hash code, could be more sophisticated
}
Set<Edge> adjacencyList = new HashSet<Edge>();
Try L1.get(i).add(whatever);, and of course first check whether L1.get(i) exists, otherwise add that inner list first.
It's something like this:
List<List<Integer>> L1 = new ArrayList<List<Integer>>(); //better use interfaces
List<Integer> first = null;
if( L1.size() > 0) {
first = L1.get(0); //first element
}
else {
first = new ArrayList<Integer>();
L1.add(first);
}
first.add(4711); //or whatever you like to add
List<List<Integer>> L1 = new ArrayList<ArrayList<Integer>>();
List<Integer> list1 = new ArrayList<Integer>();
list1.add(1);
list1.add(2);
list1.add(3);
list1.add(4);
list1.add(5);
//add list to the list
L1.add(list1);
iterate over the list of lists
for( List<Integer> list: L1 ){
for(Integer i:list){
System.out.println(i);
}
}
You can only add objects of type ArrayList to L1. So you could do this:
ArrayList<ArrayList<Integer>> firstList = new ArrayList<ArrayList<Integer>>();
ArrayList<Integer> secondList = new ArrayList<Integer>();
secondList.add(0);
firstList.add(secondList);
L1.add(new ArrayList<Integer>());
will create a new List within the first list. Then you can
L1.get(0).add(5)
To add a new element to the outer array:
ArrayList<Integer> inner = new ArrayList<Integer>();
L1.add(inner);
Then to add element to the inner array:
int exampleInt = 10;
ArrayList<Integer> inner = L1.get(0);
inner.add(exampleInt);
To traverse all elements in all arrays:
for (ArrayList<Integer> inner : L1)
{
for (Integer element : inner)
{
System.out.println(element);
}
}

Categories

Resources