I made this Code:
Class class{
public void main(String args[]){
ArrayList<ArrayList>list = new ArrayList<>();
ArrayList<String> Stringlist1 = new ArrayList<>();
ArrayList<String> Stringlist2 = new ArrayList<>();
Stringlist1.add("A");
Stringlist1.add("C");
Stringlist1.add("B");
Stringlist2.add("tr");
Stringlist2.add("rgd");
Stringlist2.add("sg");
}}
and i want to get the items from the inner list like:
for(ArrayList<String> ArrList: list){
ArrList.get(0)
}
pleas tell me how to do this!
ArrayList<ArrayList<String>> list = new ArrayList<>();
ArrayList<String> stringlist1 = new ArrayList<>();
ArrayList<String> stringlist2 = new ArrayList<>();
list.add(stringlist1);
list.add(stringlist2);
stringlist1.add("A");
stringlist1.add("C");
stringlist1.add("B");
stringlist2.add("tr");
stringlist2.add("rgd");
stringlist2.add("sg");
for(ArrayList<String> arrList: list){
for (String str : arrList) {
// do something
}
}
You can try something like this:
ArrayList<ArrayList<String>>list = new ArrayList<>();
//add items to StringLists
list.add(Stringlist1);
list.add(Stringlist2);
//Now access elements in your for loop
ArrayList<ArrayList<String>> list = new ArrayList<>();
ArrayList<String> stringlist1 = new ArrayList<>();
ArrayList<String> stringlist2 = new ArrayList<>();
stringlist1.add("A");
stringlist1.add("B");
stringlist1.add("C");
stringlist2.add("tr");
stringlist2.add("rgb");
stringlist2.add("sg");
list.add(stringlist1);
list.add(stringlist2);
//loop
System.out.println(list.get(0).get(0));
A nested for loop or for each loop is required.
You first need to add the sub lists to your parent list or you are not going to have access to the sub lists. Other than that, your code is mostly correct, except for not looping through each sub list.
The below code does exactly what you need so just copy it into your main function and it will work.
// create top level list
ArrayList<ArrayList<String>> list = new ArrayList<>();
// create sub lists
ArrayList<String> stringlist1 = new ArrayList<>();
ArrayList<String> stringlist2 = new ArrayList<>();
// add both sub lists to the parent list
list.add(stringlist1);
list.add(stringlist2);
// add elements to both lists
stringlist1.add("A");
stringlist1.add("C");
stringlist1.add("B");
stringlist2.add("tr");
stringlist2.add("rgd");
stringlist2.add("sg");
// loop through the top level list (will loop twice since the 2 elements are the sub lists)
for(ArrayList<String> array: list) {
System.out.println(array);
// loop through each element of each sub list
for (String str : array)
System.out.println(str);
}
Output:
[A, C, B]
A
C
B
[tr, rgd, sg]
tr
rgd
sg
Related
This is my first list:
String[] myList = ["john","Coding","haha","tukku", "Coding/a","Coding/a/b", "folder1/file1.txt", "folder1/folder2/file1.txt"]
String[] lst1 = ["John","Coding/*", "folder1/*"]
finallist = mylist - lst1
I want to remove all the files from myList which have their parent folder name in lst1
expected result
["haha", "tukku"]
If you change lst1 to regular expression then code could be quite simple..
def mylist = ["john","Coding","haha","tukku", "Coding/a","Coding/a/b", 'folder1/file1.txt', 'folder1/folder2/file1.txt']
lst1 = ["john", "Coding/*", "folder1/*"]
def re = lst1.collect{ it.replaceAll('\\*', '.*') }.join('|')
// re = "john|Coding/.*|folder1/.*"
def finallist = mylist.findAll{ !(it==~re) }
This would be one solution. I did not use any streams to keep the solution simple:
String[] myList = {"john","Coding","haha","tukku", "Coding/a","Coding/a/b", "folder1/file1.txt", "folder1/folder2/file1.txt"};
String[] filterList = {"john","Coding/*", "folder1/*"};
ArrayList<String> result = new ArrayList<>();
for(String listElement: myList) // Iterating over each list element
{
String elementParent = listElement.split("/")[0]; // Getting the first parent (the first string before /)
boolean toBeAdded = true; // Variable that keeps track whether this element has to be added to result or not
for(String filterStr: filterList)
{
String filterParent = filterStr.split("/")[0]; // Getting the parent of the Filter String.
if(elementParent.toLowerCase().equals(filterParent.toLowerCase())) // If The element parent and the filter parent are the same, then we do not add it.
{
toBeAdded = false;
break;
}
}
if(toBeAdded)
{
result.add(listElement);
}
}
System.out.println(result);
And this is the output:
[haha, tukku]
I want to merge two corresponding values of two different variables with comma separator in a row :
like
Plate Numbers(Output) : MH 35353, AP 35989, NA 24455, DL 95405.
There is two different variables one is plate State and another is plate Number, I want to merge them together with their corresponding values like 1st values of plate State with 1st value of plate Number after that comma then so on..
I tried this code snippet but didn't work :
ArrayList<String>
list1 = new ArrayList<String>();
list1.add("MH");
list1.add("AP");
list1.add("NA ");
list1.add("DL");
ArrayList<String>
list2 = new ArrayList<String>();
list2.add("35353");
list2.add("35989");
list2.add("24455");
list2.add("95405");
list1.addAll(list2);
use this :
ArrayList<String>
list1 = new ArrayList<String>();
list1.add("MH");
list1.add("AP");
list1.add("NA ");
list1.add("DL");
ArrayList<String>
list2 = new ArrayList<String>();
list2.add("35353");
list2.add("35989");
list2.add("24455");
list2.add("95405");
Iterator iterable = list2.iterator();
List<String> list3 =list1.stream()
.map(x->{
x= x+" "+((String) iterable.next());
return x;})
.collect(Collectors.toList());
String output = String.join(", ", list3);
System.out.println(output);
From ArrayList#addAll Javadoc:
Appends all of the elements in the specified collection to the end of this list[...]
This is not what you want, because you actually don't want to append the objects, you want to merge the String of the first list with the String from the second list. So in a sense, not merge the List but merge the objects (Strings) in the lists.
The easiest (most beginner friendly) solution would be to just create a simple helper method yourself, that does what you need.
Something like this:
public static void main(String[] args) {
ArrayList<String> list1 = new ArrayList<String>();
list1.add("MH");
list1.add("AP");
list1.add("NA");
list1.add("DL");
ArrayList<String> list2 = new ArrayList<String>();
list2.add("35353");
list2.add("35989");
list2.add("24455");
list2.add("95405");
ArrayList<String> combined = combinePlateNumbers(list1, list2);
System.out.println(combined);
}
private static ArrayList<String> combinePlateNumbers(List<String> list1, List<String> list2) {
ArrayList<String> result = new ArrayList<>();
if (list1.size() != list2.size()) {
// lists don't have equal size, not compatible
// your decision on how to handle this
return result;
}
// iterate the list and combine the strings (added optional whitespace here)
for (int i = 0; i < list1.size(); i++) {
result.add(list1.get(i).concat(" ").concat(list2.get(i)));
}
return result;
}
Output:
[MH 35353, AP 35989, NA 24455, DL 95405]
Hi I have an arraylist of arraylist in this format:
[[val1, val2],[val3,val4],[val1,val2],[val1,val5]]
and would like to get the unique set of arraylists:
[[val1, val2],[val3,val4],[val1,val5]]
I have tried the following:
Set<String> uniques = new HashSet<>();
for (ArrayList<String> sublist : mappedEntities) {
uniques.addAll(sublist);
}
but this merges all the values of the internal arraylist together
can use Java 8 Collection Stream Distinct,
return in Set datatype :
Set<List<String>> uniques = mappedEntities.stream().distinct().collect(Collectors.toSet());
if you want return in List :
List<List<String>> uniques = mappedEntities.stream().distinct().collect(Collectors.toList());
Why not simply put them in a Set like this?
Set<List<String>> uniques = new HashSet<>(mappedEntities);
Your mistake is that you are flattening the inner lists and putting their items in the set separately.
The issue here is that you need a Set of ArrayList Set<ArrayList<String>>, but you are using a Set of Strings Set<String> instead.
Given the list :
List<List<String>> mappedEntities = Arrays.asList(Arrays.asList("val1", "val2"),
Arrays.asList("val3", "val4"),
Arrays.asList("val1", "val2"),
Arrays.asList("val1", "val5"));
All you need to do is just declare the set and use the addAll().
Set<List<String>> mySet = new HashSet<>();
mySet.addAll(mappedEntities);
Since a set can hold only unique values, all duplicates will not be added to the set (No need to explicitly check this). You can now print it out :
mySet.forEach(System.out::println);
Or more simply, initialize the HashSet using the list mappedEntities :
Set<List<String>> mySet = new HashSet<>(mappedEntities);
I am beginner on STACKOVERFLOW but i to try solve your problem
I think you want like this..
import java.util.*;
public class GFG {
public static void main(String[] args)
{
int n = 3;
// Here aList is an ArrayList of ArrayLists
ArrayList<ArrayList<String> > aList =
new ArrayList<ArrayList<String> >(n);
// Create n lists one by one and append to the
// master list (ArrayList of ArrayList)
ArrayList<String> a1 = new ArrayList<String>();
a1.add("1");
a1.add("2");
aList.add(a1);
ArrayList<String> a2 = new ArrayList<String>();
a2.add("11");
a2.add("22");
aList.add(a2);
ArrayList<String> a3 = new ArrayList<String>();
a3.add("1");
a3.add("2");
aList.add(a3);
Set<ArrayList<String>> uniques = new HashSet<ArrayList<String>>();
for (ArrayList<String> sublist : aList) {
uniques.add(sublist);
}
System.out.println("Your Answer");
for (ArrayList<String> x : uniques)
System.out.println(x);
}
}
try this code:
public class B {
public static void main(String[] args) throws Exception {
List<List<String>> list= Arrays.asList(
Arrays.asList("a","b","c"),
Arrays.asList("a","b","c"),
Arrays.asList("a","b","c","d"));
Set<List<String>> uniques = new HashSet<>();
for (List<String> sublist : list) {
if(!uniques.contains(sublist))
uniques.add(sublist);
}
System.out.println(uniques);
}
}
output:
[[a, b, c], [a, b, c, d]]
I have two patterns of lists inside a big list.
[[5.35, 5.09, 4.95, 4.81, 4.75, 5.19], [3601.0, 3602.0, 3603.0, 3600.0, 3610.0, 3600.0],[..,..,..,],[..,..,..],...]
To put in simple words, it is a combination of
[ [pricesList1], [DurationList1], [PricesList2], [DurationList2],... ]
I now want to create a new list with the price and corresponding duration from both lists as a pair from each set. For Example :
[[[5.35,3601.0],[5.09,3602.0],[4.95,3603],[4.81,3600],[4.75,3610],....],[[p1,d1],[p2,d2],[p3,d3],..],[[],[],[],..],....]
I have tried using List<List<Object>> and List<List<String>>. But no use. How can I do this?
I programed as following, which is wrong :
List<List<Object>> DurationList = new ArrayList<List<Object>>();
List<List<Object>> FinalList = new ArrayList<List<Object>>();
List<List<String>> SlotList = null;
for(int pair=0; pair<(FinalList.size()-1) ; pair=pair+2)
{
for(int innerloop=0; innerloop<(FinalList.get(pair).size());innerloop++)
{
SlotList = new ArrayList<List<String>>();
SlotList.addAll((Collection<? extends List<String>>) (FinalList.get(pair).get(innerloop)));
}
}
for(int pair=1; pair<(FinalList.size()) ; pair=pair+2)
{
for(int innerloop=0; innerloop<(FinalList.get(pair).size());innerloop++)
{
SlotList.addAll((Collection<? extends List<Object>>) FinalList.get(pair).get(innerloop));
}
}
Assuming the input list always has an even number of sublists and pairs of sublists have the same size, you can use a for loop iterating over the outer lists's element two by two :
List<List<String>> result = new ArrayList<>();
for (int i=0; i<outerList.size(); i+=2) {
List<String> priceList = outerList.get(i);
List<String> durationsList = outerList.get(i+1);
for (int j=0; j<priceList.size(); j++) {
List<String> newEntry = new ArrayList<>();
newEntry.add(priceList.get(j));
newEntry.add(durationsList.get(j));
result.add(newEntry);
}
}
As commented I suggest defining your own class to store the price and duration rather than using that List<String> newEntry.
Now I can get list A, list B. And I want to get a new list which is A-(intersection of A and B). But when I get the intersection, it is [].
List<Map<String,String>> userDevices = clientdeviceService.getUserDevice(userId);
List<String> selectedDevices = new ArrayList<String>(Arrays.asList(devices));//selectedDevices is------[stress0012,stress0014,]
List<String> originalDevices = new ArrayList<String>();
List<String> originalDevicesRetain = new ArrayList<String>();//copy for operating
for(Map<String,String> originalDevId : userDevices){
originalDevices.add(originalDevId.get("DEVID"));
}
originalDevicesRetain.addAll(originalDevices);
originalDevicesRetain.retainAll(selectedDevices);
//originalDevicesRetain now is [],and it return false.
originalDevices.removeAll(originalDevicesRetain);
if(!originalDevices.isEmpty()){
}
Why originalDevices is [] has no elements in it?