I have two ArrayLists. The first list contains some x number of elements these elements are again ArrayLists. The second list contains only integer values.
Second list size is always less than first list size Example of first list is: [[TC1,TC1_1],[,TC1_2],[TC2,TC2_1],[TC3,TC3_1][,TC3_2],[TC4,TC4_1][,TC4_2][,TC4_3],[TC5,TC5_1],[TC6,TC6_1]]
Example of second list is [0,2,3,5,8,9].This second Araylist elements points to 1st arraylist where the 1st element of individual ArrayList elements of first arraylist is not empty
Now the requirement is 1st list should be split into 6 lists where 6 is 2nd list size. Output should be as below.
Of the 6 new lists 1st list would contain elements of main list from 0th to 1st index. The 2nd list would contain elements of main list from 3rd index. The 3rd list would contain elements of main list from 4th to 5th index and so on..finally output will be as below
`[[[TC1,TC1_1],[,TC1_2]]
[[TC2,TC2_1]]
[[TC3,TC3_1][,TC3_2]]
[[TC4,TC4_1][,TC4_2][,TC4_3]]
[[TC5,TC5_1]]
[[TC6,TC6_1]]]
private ArrayList getTCsIncludingSubTcs(ArrayList TCIndexes,ArrayList alTCs) {
//List tempSubList=new ArrayList();
ArrayList finalTCS=new ArrayList();
for(int j=0;j<TCIndexes.size();j++){
int TCIndex=(int)TCIndexes.get(j);
if(j==0 && TCIndexes.size()==1){
//List tempSubList=new ArrayList(alTCs.subList(TCIndex,(int)alTCs.size()));
List tempSubList=getSubArrayList(TCIndex,(int)alTCs.size(),alTCs);
finalTCS.add(tempSubList);
break;
}
int nextTCIndex=j+1;
System.out.println(nextTCIndex);
if(j==TCIndexes.size()-1){
List tempSubList=getSubArrayList(TCIndex,(int)alTCs.size(),alTCs);
finalTCS.add(tempSubList);
break;
}
List tempSubList=getSubArrayList(TCIndex,(int)alTCs.size(),alTCs);
finalTCS.add(tempSubList);
System.out.println("finalTCS :"+finalTCS);
}
System.out.println("fc size"+finalTCS.size());
return finalTCS;
}
Try this code.
public class Test {
private List<List<String>> getTcsIncludingSubTcs(ArrayList<Integer> tcIndexes,ArrayList<String> alTcs) {
List<List<String>> finalTcs=new ArrayList<>();
List<String> temp = new ArrayList<>();
int size = tcIndexes.size();
int i= alTcs.size();
int k = 0;
for(int j=0; j<alTcs.size(); j++){
if(( j != 0 && j % size == 0 && i >= size))
{
temp = new ArrayList<>();
k++;
}
i--;
temp.add(alTcs.get(j));
if(finalTcs.contains(temp))
finalTcs.remove(k);
finalTcs.add(k, temp);
}
return finalTcs;
}
public static void main (String arg[])
{
ArrayList<String> data1 = new ArrayList<>();
data1.add("TC1");
data1.add("TC2");
data1.add("TC3");
data1.add("TC4");
data1.add("TC5");
data1.add("TC6");
data1.add("TC7");
data1.add("TC8");
data1.add("TC9");
data1.add("TC10");
ArrayList<Integer> data2 = new ArrayList<>();
data2.add(0);
data2.add(3);
data2.add(6);
Test t = new Test();
List<List<String>> list = t.getTcsIncludingSubTcs(data2, data1);
for(List<String> l : list)
System.out.println(l);
}
}
Output:
[TC1, TC2, TC3]
[TC4, TC5, TC6]
[TC7, TC8, TC9, TC10]
One more solution is ,
we have source list and start index list.Using these two lists generate end index list.Now use start index list and end index list to generate the required final output
Related
Input:
mainList= ArrayList size = 4: 0 = {
expression = ArrayList size = 8: 0 = {
names: "name"
values: ArrayList size = 1: {
0: "value"
}
}
}
I need to iterate over this ArrayList and create 2 new ArrayLists 1 containing a List of Strings from names and 1 containing the list of Strings from values
Data structure explanation:
mainList contains an ArrayList of 4 entries, each entry is an ArrayList called expressions which has 8 entries, each entry has a String value 'names' and an ArrayList called 'values' which has a single String value.
I have tried:
List<String> names = new ArrayList<>();
List<String> values= new ArrayList<>();
for(int i=0; i < mainList.size(); i++) {
names.add(mainList.get(i));
for(int i=0; i < names.size(); i++) {
values.add(names.get(i));
}
}
Desired Output:
names = ArrayList size = 8 {name1, name2...name8};
values = ArrayList size = 4 {values1, values2...values4};
I am building a mind game, it's hard to explain so I put an example.
I have a list of words (it can be infinite):
String myList[] = {"chair", "house", "ocean", "plane", "dog", "TV", "grass", "money" etc....}
Now the tricky part, I need to build 4 lists of pair index/word (every list has the same size) randomly but that fit these rule:
if I chose a number, the word that match this number only appears in 2 lists.
for example this would be correct:
List1:
1/chair
2/house
3/plane
4/grass
List2
1/chair
2/dog
3/plane
4/TV
List3:
1/ocean
2/house
3/money
4/TV
List4
1/ocean
2/dog
3/money
4/grass
For example:
If I pick number 3, then list 3 and list 4 match the word 'money', list 1 and 2 match the word 'plane'. There always must be 2 matching lists (never less, never more). They should be build from a huge array of words randomly, so you can't guess which list will be matching when you pick a number.
I tried to do it with a nice simple recursive algorithm. But I badly failed.
My initial approach to this problem would be to
Select a random word in the universe
Assign the selected word to two lists that
are different and
are not full
Store the random word in a set of closed words in case it is selected again
Rinse and repeat until all lists are full
Something like this should do the trick (you can change the provided words and the respective listSize accordingly). The number of words should be dividable by the listSize in order to fill up all lists.
public static void main(String[] args) {
String[] words = new String[] { "chair", "house", "ocean", "plane",
"dog", "TV", "grass", "money" };
// valid list sizes for 8 words: 1, 2, 4, 8
int listSize = 4;
List<String[]> result = distributeRandomly(words, listSize);
for (String[] resultList : result) {
for (int index = 0; index < listSize; index++) {
System.out.println((index + 1) + "/" + resultList[index]);
}
System.out.println();
}
}
private static List<String[]> distributeRandomly(String[] words, int listSize) {
// each word goes into 2 lists, so how many lists do we need?
int listCount = words.length * 2 / listSize;
if (listCount * listSize != words.length * 2) {
throw new IllegalArgumentException("Number of words"
+ " must be a multiple of the size of the individual lists!");
}
// initialize result lists (here arrays) in fitting size
List<String[]> listsToFill = new ArrayList<String[]>(listCount);
for (int index = 0; index < listCount; index++) {
listsToFill.add(new String[listSize]);
}
// be sure to randomly pick the given words by shuffling them
List<String> shuffledWords = new ArrayList<String>(Arrays.asList(words));
Collections.shuffle(shuffledWords);
List<String[]> result = new ArrayList<String[]>(listCount);
int maxWordPosition = listSize - 1;
// distribute words
for (String word : shuffledWords) {
// word is supposed to be inserted in two lists at the same index
int wordPosition = -1;
// iterate result lists
Iterator<String[]> listIterator = listsToFill.iterator();
while (listIterator.hasNext()) {
String[] list = listIterator.next();
if (wordPosition == -1) {
// look out for the first list with an empty slot
for (int index = 0; index < listSize; index++) {
if (list[index] == null) {
// found empty slot at this index
wordPosition = index;
// insert word here (first list)
list[wordPosition] = word;
if (wordPosition == maxWordPosition) {
// the list is full, no more empty slots here
listIterator.remove();
result.add(list);
}
break;
}
}
} else if (list[wordPosition] == null) {
// found second list with an empty slot at the same index
list[wordPosition] = word;
if (wordPosition == maxWordPosition) {
// the list is full, no more empty slots here
listIterator.remove();
result.add(list);
}
// we are done with this word
break;
}
}
// shuffle result lists again, to ensure randomness
Collections.shuffle(listsToFill);
}
return result;
}
This produces (for example) the following output:
1/grass
2/TV
3/plane
4/ocean
1/grass
2/dog
3/money
4/chair
1/house
2/dog
3/money
4/ocean
1/house
2/TV
3/plane
4/chair
what command of arraylist should I use in order to get rid of adjacent Strings. Suppose I have an arraylist of allOrders<String>:
Crushed Turtle
10 Coins Off
10 Coins Off
Mushroom Veal
In the example above I should not get 2 adjacent lines of the same thing. What method of arraylist should I use?
Note: only adjacent should be removed/replaced. The following is legit:
Firey Flower Pasta
Crushed Turtle
Firey Flower Pasta
Crushed Turtle
You can get an Iterator from your List, iterate over the entire list and keep track of the latest value. If the current value is equal to the latest, you delete it.
Something like this:
Iterator<String> iterator = allOrders.iterator();
String latest = "";
while (iterator.hasNext()) {
String current = iterator.next();
if (current.equals(latest)) {
iterator.remove();
}
latest = current;
}
There is no built-in method for doing what you want, but you could create a stripped copy (stripped) of your list like this:
List<String> stripped = new ArrayList<String>();
String latestOrder = null;
for (String order : allOrders) {
if (!order.equals(latestOrder)) {
stripped.add(order);
}
latestOrder = order;
}
Write your own loop which will iterate over pair of elements and if they are equal remove one of them (you can use remove(index) from List).
for (int i=list.size()-1; i>0; i--){
if (list.get(i-1).equals(list.get(i))){
list.remove(i);
}
}
I prefer to iterate from end to start to avoid problems with elements shifting.
DEMO:
List<String> list = new ArrayList<>();
list.add("Crushed Turtle");
list.add("10 Coins Off");
list.add("10 Coins Off");
list.add("10 Coins Off");
list.add("Mushroom Veal");
for (int i = list.size() - 1; i > 0; i--) {
if (list.get(i - 1).equals(list.get(i))) {
list.remove(i);
}
}
System.out.println(list);
Output: [Crushed Turtle, 10 Coins Off, Mushroom Veal]
This works. You iterate over the List and compare consecutive elements if two equals you remove one of them.
ArrayList<String> l = new ArrayList<String>();
l.add("a");
l.add("b");
l.add("b");
l.add("b");
l.add("b");
l.add("d");
System.out.println(l);
for(int i = 0; i < l.size() - 1; i++){
if(l.get(i).equals(l.get(i+1))){
l.remove(i+1);
i--;
}
}
System.out.println(l);
I need to first access and then compare elements from two separate lists and based on whichever element has the smaller value, remove the lesser element and assign it a position within a third list. How do I accomplish this?
I believe you can just add the elements of both the list in a new list of one of the list and then sort it in ascending order e.g. below(pseudo code):
List<Integer> list1 = Arrays.asList(2,4,5);
List<Integer> list2 = Arrays.asList(2,6,8,9,12,56);
List<Integer> mergedList = new ArrayList<Integer>();
mergedList.addAll(list1);
mergedList.addAll(list2);
Collections.sort(mergedList);
Now mergedList should have sorted elements.
Just for your learning, find a sample manual merge program below:
List<Integer> list1 = Arrays.asList(2,4,5);
List<Integer> list2 = Arrays.asList(2,6,8,9,12,56);
List<Integer> mergedList1 = new ArrayList<Integer>();
mergedList1.add(list1.get(0));
for(int indx = 1; indx< list1.size(); indx++){
int valueToMerge = list1.get(indx);
boolean merged = false;
for(int indx1 = 0; indx1< mergedList1.size(); indx1++){
if(mergedList1.get(indx1) > valueToMerge){
//add the value in middle
mergedList1.add(indx1, valueToMerge);
merged = true;
break;
}
}
if(!merged){
//add the value in the end
mergedList1.add(valueToMerge);
}
}
for(int valueToMerge: list2){
boolean merged = false;
for(int indx1 = 0; indx1< mergedList1.size(); indx1++){
if(mergedList1.get(indx1) > valueToMerge){
//add the value in middle
mergedList1.add(indx1, valueToMerge);
merged = true;
break;
}
}
if(!merged){
//add the value in the end
mergedList1.add(valueToMerge);
}
}
I've two lists A and B. I'd like to find out indexes of elements in A that match elements of listB. Something like this:
ArrayList listA = new ArrayList();
listA.add(1);listA.add(2);listA.add(3);listA.add(4);
ArrayList listB = new ArrayList();
listB.add(2);listB.add(4);
ArrayList listC = new ArrayList();
for(int i=0; i<listB.size();i++) {
int element = listB.get(i);
for(int j=0; j<listA.size(); j++) {
if(listA.get(j) == element) listC.add(j);
}
}
I guess that's one ugly way to doing it. What is the best way to finding all the indexes of A that match all elements in B? I believe there exists a method called containsAll in collections api - don't think it returns matching indexes.
If you had to use an ArrayList, you could create a HashSet from the ArrayList. This would make the call to contains O(1). It would take O(n) to create the HastSet. If you could start with a HashSet, that would be best.
public static void main(String[] args)
{
List listA = new ArrayList();
listA.add(1);
listA.add(2);
listA.add(3);
listA.add(4);
List listB = new ArrayList();
listB.add(2);
listB.add(4);
Set hashset = new HashSet(listA);
for(int i = 0; i < listB.size(); i++)
{
if(hashset.contains(listB.get(i)))
{
listC.add(i);
System.out.println(i);
}
}
}
The Guava libraries come with a method
"SetView com.google.common.collect.Sets.intersection(Set a, Set b)
that will give the elements contained in both sets, but not the indexes. Although it should be easy to get the indexes afterwards.
Simple:
List<Integer> listA = new ArrayList<Integer>();
listA.add(1);
listA.add(2);
listA.add(3);
listA.add(4);
List<Integer> listB = new ArrayList<Integer>();
listB.add(2);
listB.add(4);
List<Integer> listC = new ArrayList<Integer>();
for ( Integer item : listA ) {
int index = listB.indexOf( item );
if ( index >= 0 ) {
listC.add(index);
}
}
But this only works if there is no repetition, if there are repeated indexes you have to do it the way you did, navigating the full list.
EDIT
I thought you wanted the elements, not indexes, sets are not going to give you indexes, only the elements.
Assuming there's no duplicate values, why not use ArrayList.indexOf?
public final class ArrayListDemo {
public static void main(String[]args){
findIndices(createListA(), createListB());
}
private static final List<Integer> createListA(){
List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(3);
list.add(5);
return list;
}
private static final List<Integer> createListB(){
List<Integer> list = new ArrayList<Integer>();
list.add(0);
list.add(2);
list.add(3);
list.add(4);
return list;
}
private static void findIndices(List<Integer> listA, List<Integer> listB){
for(int i = 0; i < listA.size(); i++){
// Get index of object in list b
int index = listB.indexOf(listA.get(i));
// Check for match
if(index != -1){
System.out.println("Found match:");
System.out.println("List A index = " + i);
System.out.println("List B index = " + index);
}
}
}
}
Output
Found match:
List A index = 1
List B index = 2
If list A and list B are sorted in the same order (I'll assume ascending, but descending works as well) this problem has an O(n) solution. Below is some (informal, and untested) code. When the loop exits, indexMap should contain the indices of every element in list A that match an element in list B and the index of the matched element in list B.
int currentA;
int currentB;
int listAIndex = 0;
int listBIndex = 0;
Map<Integer, Integer> indexMap = new HashMap<Integer, Integer>();
currentA = listA.get(listAIndex);
currentB = listB.get(listBIndex);
while ((listAIndex < listA.length) && (listBIndex < listB.length))
{
if (currentA == currentB)
{
indexMap.put(listAIndex, listBIndex);
++listAIndex;
}
else if (currentA < currentB)
{
++listAIndex;
}
else // if (currentA > currentB)
{
++listBIndex;
}
}
Using Apache CollectionUtils, there are plenty of options