ArrayList iteration specific list - java

I have an arraylist in which
ArrayList<ArrayList<String>> listofItems=new ArrayList<ArrayList<String>>();
in the list of items I have items like this
[[1][2][3][4][5][6][7][8][9][10][11][12][13][14][15][16][17][18][19][20][21][22]]
how to iterate and store in another array these values split into two like
[1,2,3,4,5,6,7,8,9,10,11] and [11,12,13,14,15,16,17,18,19,20,21,22]. I have used advanced for loop
for(ArrayList<String> list:listofItems)
{
for (String s:list)
{
//I dont know how to add logic here.
}
}

I am assuming here that both lists will also hold string type data.If you want Integer type,you can parse while adding.
ArrayList<ArrayList<String>> listofItems = new ArrayList<ArrayList<String>>();
ArrayList<String> list1 = new ArrayList<String>();
ArrayList<String> list2 = new ArrayList<String>();
for (ArrayList<String> list : listofItems) {
for (String s : list) {
// there shud be some condition how much elements you want in a
// list or some condition
// to decide in which list we need to add item
if (list.size() < 12)
list1.add(s);
else
list2.add(s);
}
}

Use something like that:
if (yourlist.size()>0) {
List<String> first = yourList.subList(0, (int)Math.ceil(yourlist.size()/2.0));
List<String> second = yourList.subList((int)Math.ceil(yourlist.size()/2.0), yourlist.size());
}
Would be separate your list in 2 lists divided in the half.

You can use this code to store your list into another list.
List<String> stringList = new ArrayList<String>();
for(ArrayList<String> list:listofItems) {
for (String s:list) {
stringList.add(s);
}
}

In this case, when you add info to listOfItems, you should try example like this
for(int i = 0; i< 2; i++){
for(int j = 0; j < n; j++){
/// add util break n
lists.get(i).add(strTemp);
}
}
You can change i < 2 into any number you want. I only make this sample for you.

Related

Grouping the nested loop elements based on the first iteration variable in Java

I have 2 lists one for the sentence one for the keywords. The idea is to check if the sentence have the keywords. and put them in a list for each sentence in order.
I am sorry if this is already duplicated here in advance.
List <String> sentence= new ArrayList <>();
sentence.add("this is a good dog");
sentence.add("cats drink milk");
sentence.add("Animals are beautiful creatures");
List <String> keyword= new ArrayList <>();
keyword.add("dog");
keyword.add("cats");
keyword.add("beautiful");
keyword.add("good");
keyword.add("are");
keyword.add("this");
keyword.add("milk");
My idea was to create 2 nested loops for each list:
for (int b = 0; b < sentence.size(); b++) {
for (int c = 0; c < keyword.size(); c++) {
if (sentence.get(b).contains(keyword.get(c))) {
System.out.println(keyword.get(c));
}
}
}
The output of this is:
dog
good
this
cats
milk
beautiful
are
The desired output would be:
[this,good,dog]
[cats,milk]
[are,beautiful]
So it is like getting all the existing keywords, in the order of the sentence,not related to keywords order.
and then group the existing keywords for each sentence, as in the order of existence.
Hope it is clear. Would really appreciate any ideas. doesnt have to follow the same method.
Iterate over your sentence list. For each sentence iterate over your keyword list. Add each found keyword found in a tempList, sort the tempList by the index of keyword in sentence and finally add each tempList to a list of lists. Example:
public static void main(String[] args) {
List <String> sentence= new ArrayList <>();
sentence.add("this is a good dog");
sentence.add("cats drink milk");
sentence.add("Animals are beautiful creatures");
List <String> keyword= new ArrayList <>();
keyword.add("dog");
keyword.add("cats");
keyword.add("beautiful");
keyword.add("good");
keyword.add("are");
keyword.add("this");
keyword.add("milk");
List<List<String>> result = new LinkedList<>();
for(String sen: sentence){
List<String> tempList = new ArrayList<>();
for(String key: keyword){
if(sen.contains(key)){
tempList.add(key);
}
}
tempList.sort(new Comparator<String>() {
#Override
public int compare(String o1, String o2) {
return sen.indexOf(o1) - sen.indexOf(o2) ;
}
});
result.add(tempList);
}
for(List<String> r : result){
System.out.println(r);
}
}
You need a slight modification in your looping
for (int i = 0; i < sentence.size(); i++) {
String[] matchArray = new String[sentence.get(i).split(" ").length];
for (int j = 0; j < keyword.size(); j++) {
if (sentence.get(i).contains(keyword.get(j))) {
matchArray[Arrays.asList(sentence.get(i).split(" ")).indexOf(keyword.get(j))] = keyword.get(j);
}
}
List<String> matchList = new ArrayList<String>();
for(String match: matchArray) {
if(match != null) {
matchList.add(match);
}
}
System.out.println(matchList);
}
For every sentence create an array with size same as the sentence (just to ensure size). Now when matches are found get the index of the match from sentence and add element to that particular index of the array. So at the end of keyword iteration you will have all matches in array with null values if some words are not matching.
Now declare a new List of String into which add the elements from array which are not null. At last print the list.
I think Map would be a good choice here. Just make sentences keys for the map and keywords as value. Following is the code for the same.
Map <String, ArrayList<String>> sentences= new HashMap<>();
sentences.put("this is a good dog", new ArrayList<>());
sentences.put("cats drink milk", new ArrayList<>());
sentences.put("Animals are beautiful creatures", new ArrayList<>());
List <String> keyword= new ArrayList <>();
keyword.add("dog");
keyword.add("cats");
keyword.add("beautiful");
keyword.add("good");
keyword.add("are");
keyword.add("this");
keyword.add("milk");
keyword.forEach(word -> sentences.entrySet().stream()
.filter(map -> map.getKey().contains(word)).
forEach(map -> sentences.computeIfAbsent(map.getKey(), key->new ArrayList<>()).add(word)));
sentences.forEach((key, value) -> System.out.println(value));
Try something like this:
for (String sen: sentence) {
System.out.print("[");
boolean first = true;
for (String word: sen.split("[\\s\\p{Punct}]")) {
if (keyword.contains(word)) {
if (first) {
first = false;
} else {
System.out.print(",");
}
System.out.print(word);
}
}
System.out.println("]");
}
this should do it, printing exactly in the format you requested :
for (int b = 0; b < sentence.size(); b++) {
String arr[] = sentence.get(b).split("\\s+");
List result = new ArrayList<>();
for (int c = 0; c < arr.length; c++ ) {
if (keyword.contains(arr[c]))
result.add(arr[c]);
}
System.out.println(result);
}
I would use the following :
for(String currentSentence : sentence) {
List<String> keywordsInSentence = new ArrayList<>();
for (String word : currentSentence.split("\\s+")) {
if (keyword.contains(word)) {
keywordsInSentence.add(word);
}
}
System.out.println(keywordsInSentence);
}
You can try it here.
(and I'd rename sentence into sentences or sentenceList and similarly for keyword, otherwise it's just confusing)
If you need to do anything more to the keywords than immediately displaying them, you could insert the keywordsInSentence lists into a Map<String, List<String>> you would value by replacing the System.out.println by map.put(currentSentence, keywordsInSentence).

Break ArrayList into ArrayList of ArrayLists dynamically

I am trying to make a method to breakdown an arrayList of objects into multiple arrayLists based on an attribute value of the myObj class.
private static ArrayList<ArrayList<Ticket>> splitList(ArrayList<Ticket> arrayList){
ArrayList<ArrayList<Ticket>> smallLists = new ArrayList<>();
for(int i = 0; i < arrayList.size(); i++){
for(Ticket eachTick: Ticket.getTickets()){
if(arrayList.get(i).getCategory().equals(eachTick.getCategory())){
smallLists.add(...);
}
}
}
return smallLists;
}
If there is a better way to do what I am attempting, please advise me.
Are you trying to create a list for each ticket category found in the input list? If that's the case, then I agree with Dawood ibn Kareem: use a map that looks up the proper list based on the category. Something like this:
private static ArrayList<ArrayList<Ticket>> splitList(ArrayList<Ticket> inputList) {
Map<String, ArrayList<Ticket>> map = new HashMap<>();
// your ticket categories here
// (array used for simplicity; you should use a Set, and you should also maintain the valid categories inside your Ticket class, not here)
String[] categories = new String[] {'a', 'b', 'c' };
for (int i = 0; i < categories.length; i++) {
map.put(categories[i], new ArrayList<Ticket>());
}
for (int i = 0; i < inputList.size(); i++) {
Ticket t = inputList.get(i);
map.get(t.getCategory()).add(t);
}
// Convert to list of lists
return new ArrayList<>(map.values());
}

Class not showing up in run configurations?

I have a simple class that takes out items that were already in another array from the first array, by putting it into a list. Whenever I run this program though, another program that I created starts to run. I have tried to change the run configuration as well, but it doesn't show up on the list..? Here is the code:
package collections;
import java.util.*;
public class Arraystring {
public static void main(String [ ] args, int Collection, int String){
String[] things = { "eggs", "lasers", "hats", "pie" };
List<String> list1 = new ArrayList<String>();
for (String x : things){ //enhanced for loop
list1.add(x);
}
System.out.println(list1);
String[] thingstwo = { "lasers", "hats" };
List<String> list2 = new ArrayList<String>();
for(int i = 0;i<list2.size(); /* size for list, length for array */ i++) //regular for loop
{
list2.add(thingstwo[i]);
}
//print list one
for(int i = 0;i<list1.size(); /* size for list, length for array */ i++) //regular for loop
{
System.out.println(list1.get(i)); //Use .get for lists instead of []
}
editlist(list1, list2);
System.out.println();
//print list one
for(int i = 0;i<list1.size(); /* size for list, length for array */ i++) //regular for loop
{
System.out.println(list1.get(i)); //Use .get for lists instead of []
}
}
public static void editlist(Collection<String> l1, Collection<String> l2){
Iterator<String> it = l1.iterator(); //Goes through each list item by item
while (it.hasNext()){
if(l2.contains(it.next())){
it.remove();
}
System.out.println(it);
}
}
}
Thanks for helping, I really appreciate it.
You can execute Run file command from menu/shortcut or change main project in the IDE.
Specify yours IDE and proper shortcuts/commands would be given to you.
Upd.
You have error in yours logic:
String[] thingstwo = {"lasers", "hats"};
List<String> list2 = new ArrayList<>();
for (int i = 0; i < list2.size(); i++)
list2.add(thingstwo[i]);
Look at it line-by-line:
String[] thingstwo = {"lasers", "hats"};
Defining array, ok.
List<String> list2 = new ArrayList<>();
Defining list of strings, ok.
for (int i = 0; i < list2.size(); i++)
Looping throug items of list list2, not ok. list2 at this point is empty. Assuming you wanted to loop through thingstwo and add it's items to list2, so fixing the code:
for (int i = 0; i < thingstwo.length; i++)
And...
list2.add(thingstwo[i]);
Adding i-th item of thingstwo to list2, ok.
Running:
[eggs, lasers, hats, pie]
eggs
lasers
hats
pie
eggs
pie

get String from ArrayList

How to get String from ArrayList if my code like
ArrayList<String> PItoList = new ArrayList();
for (int i = 0; i < AllPunchList.size(); i++) {
PItoList.add(AllPunchList.get(i).toString());
}
I want to split item in ArrayList one by one.
You could do something like this:-
for(String eachString : PItoList){
// eachString.split(regex);
}
Traverse through each element in the List and do whatever you want to do in with each Element!
Try this :-
ArrayList<String> PItoList = new ArrayList<String>();
for (int i = 0; i < AllPunchList.size(); i++) {
PItoList.add((String)AllPunchList.get(i));
}
In the above example I have printed all elements in ArrayList. In this manner you can get all elements.
Then why you need split ?
Hope it will help you.

Dynamically create loops to iterate over a List of List<String>'s

I have a List of List<String>'s which I get from a external API method call:
List<List<String>> outerList
I have to create unique key combinations by concatenating strings from each list in the same order they are in the outer list.
Example: If outer list has 2 inner lists, say list1: {"A","B"} and list2: {"C","D"}. Then possible unique combinations will be AC, AD, BC and BD.
But the problem is the outerList size is dynamic, it can contain any number of inner lists. If the inner list numbers are fixed then I can write for loops and create combinations.
I am thinking in the direction of using reflections, recursion etc but so far have not been able to solve it.
public static void main(String[] args) {
List<List<String>> outerList = new ArrayList<List<String>>();
List<String> list1 = new ArrayList<String>();
list1.add("A");
list1.add("B");
List<String> list2 = new ArrayList<String>();
list2.add("C");
list2.add("D");
outerList.add(list1);
outerList.add(list2);
for(String s1: list1) {
for(String s2: list2) {
System.out.println(s1+s2);
}
}
}
Here outerList has 2 inner lists so I have created 2 for loops explicitly to iterate and concatenate. But in real-time outerList can have any number of inner lists, how to loop dynamically loop through all the inner loops and concatenate?
This code works for me:
public class Test
{
public static void generate(LinkedList<LinkedList<String>> outerList, String outPut) {
LinkedList<String> list = outerList.get(0);
for(String str : list) {
LinkedList<LinkedList<String>> newOuter = new LinkedList<LinkedList<String>>(outerList);
newOuter.remove(list);
if(outerList.size() > 1) {
generate(newOuter, outPut+str);
} else {
System.out.println(outPut+str);
}
}
}
public static void main(String[] args)
{
LinkedList<LinkedList<String>> outerList = new LinkedList<LinkedList<String>>();
LinkedList<String> list1 = new LinkedList<String>();
LinkedList<String> list2 = new LinkedList<String>();
list1.add("A");
list1.add("B");
list2.add("C");
list2.add("D");
outerList.add(list1);
outerList.add(list2);
Test.generate(outerList, "");
}
}
Output:
AC
AD
BC
BD
Sample data with enough variation to demonstrate the problem:
List<List<String>> outerList = new ArrayList<List<String>>();
List<String> innerList1 = new ArrayList<String>();
innerList1.add("A");
innerList1.add("B");
outerList.add(innerList1);
List<String> innerList2 = new ArrayList<String>();
innerList2.add("X");
innerList2.add("Y");
innerList2.add("Z");
outerList.add(innerList2);
List<String> innerList3 = new ArrayList<String>();
innerList3.add("P");
innerList3.add("Q");
innerList3.add("R");
outerList.add(innerList3);
Keep an array of counters:
int[] positions = new int[outerList.size()];
boolean another = true;
while (another) {
for (int n = 0; n < outerList.size(); n++) {
System.out.print(outerList.get(n).get(positions[n]));
}
System.out.println();
another = false;
for (int c = 0; c < outerList.size(); c++) {
positions[c]++;
if (positions[c] < outerList.get(c).size()) {
another = true;
break;
}
positions[c] = 0;
}
}
Each time around the main loop, I print one item from each inner list. Then I advance the counters, starting with the first. If that doesn't go off the end of the first inner list, we're ready to print again. But if it does, I set that counter to zero and try advancing the second one, and so on. If they all wrap round to zero, it's time to quit.
It's really just like counting except that the columns each have a different "base" (instead of all being base ten or two or whatever).

Categories