Link to home
Create AccountLog in
Avatar of usmannaeem
usmannaeem

asked on

storing the last set of objects generated by an iterator in an arraylist

Hi,

Is is possible to store the last set of objects (e.g. it.next()) in a arraylist? If yes then how is this possible?
it = set.iterator();
           while (it.hasNext()) {
           System.out.println(it.next());   
        }

Open in new window

Avatar of ksivananth
ksivananth
Flag of United States of America image


ArrayList list = new ArrayList() ;
it = set.iterator();
           while (it.hasNext()) {
           list.add(it.next());  
        }
Avatar of CEHJ
Object o = it.next();
someList.add(o);
System.out.println(o);

it = set.iterator();
Object last = null;
while (it.hasNext()) {
    last = it.next();   
}
 
if (last != null) {
    list.add(last);
}

Open in new window

(i.e. keep the Object reference in o then it can be reused)
Avatar of usmannaeem
usmannaeem

ASKER

I just want to print the final iteration from the iteration...not the everyfing the iterator generates
...
if (last != null) {
    list.add(last);
    System.out.println(last);
}
not quiet working...as I want to get the last set objects from the iterator (which is after the third iteration (s=3), I have defined it this as three in my main program)

for( int s=0; s<letters.length; s++ ){
              Set set2 = new HashSet<String>();
              Iterator it = set.iterator();
              while (it.hasNext()){
                    Object element = it.next();
                    for( int r = 0; r < letters[s].length; r++ ){
                          set2.add(p.matcher(element + letters[s][r]).replaceAll(""));
                          gats.add(element);
             }
           }
           set=set2;
           System.out.println( );
           System.out.println(s);
           it = set.iterator();

           while (it.hasNext()) {
          System.out.println(it.next());  
               }
                
      }
replaceAll takes 2 arguments - you only have one
You probably need something more like
		int ix = 0;
		while (it.hasNext()) {
			Object element = it.next();
			ix++;
			for( int r = 0; r < letters[s].length; r++ ){
				set2.add(p.matcher(element + letters[s][r]).replaceAll("X", ""));
                          	if (ix++ == 3) {
					gats.add(element);
				} // end if
             		} // end for
		} // end while

Open in new window

I do have 2 arguments, one of them is in the a top of program, as the code above is a section of my program...the above code provided by CEHJ does not seem to do the trick of adding the last iteration in to an array list. (the last iteration is dependent on the input of program, therefore it will not always be 3) Any other suggestion and help...pleaseeee
In that case, change

>>if (ix++ == 3)

to

if (ix++ == set.size() -1)
This is what is the input for this example:
String letters[][]={{"A","B"},{"A","B"},{"A","B","C","D"},{"A"}};

Below is the code for carrying out the iteration, and and trying to store only the last iteration in the arraylist:

            Pattern p = Pattern.compile("(.)(?=\\1)");
            Set set = new HashSet<String>();
            set.add("");
       
        for( int s=0; s<letters.length; s++ ){
              Set set2 = new HashSet<String>();
              Iterator it = set.iterator();
              
              int ix=0;
              
              while (it.hasNext()){
                    Object element = it.next();
                    
                    ix++;
                    for( int r = 0; r < letters[s].length; r++ ){
                          set2.add(p.matcher(element + letters[s][r]).replaceAll(""));
                                         if (ix++ == set.size() -1){
                                gats.add(element);
                          }

             }
           }
           set=set2;
           System.out.println( );
           System.out.println(s);
           it = set.iterator();
           while (it.hasNext()) {
          System.out.println(it.next());                
               }
      }

The arraylist should store the following only, which is the final iteration:
ABCA
ABA
BDA
BADA
A
BABA
ACA
BA
BACA
ADA
ABDA
BCA

This does not seem to be working for me :-(
I don't understand what you're doing - you're not even printing 'gats', which is where that last element is being stored ..?
I will print gats in other section of the program:

     System.out.println("\nThe array list");
     
                        for(Object o: gats)
                {
   
                      System.out.println(o);
                }
>>The arraylist should store the following only, which is the final iteration:

How do you know it isn't (you're only printing Sets)?
the String letters[][]={{"A","B"},{"A","B"},{"A","B","C","D"},{"A"}}  produces 3 sets...I want to store the final set in the arraylist
How do you know the final set is not in the ArrayList (you're not printing it - or at least you're not showing its contents, you're showing us the contents of something else)
I have printed the arraylist and the following is printing out incomplete and unknown set:

for(Object o: gats)
                {
   
                      System.out.println(o);
                }
Can you post here what it *does* print?
It's not going to help if you don't post the code you're actually running. What you posted last won't even compile
Below is the code...I am trying to store just iteration 3 in the arraylist

import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;
import java.util.regex.*;
 
public class gats_v1{
      public static void main(String[] args) {
            Set<String> unique = new HashSet<String>();
            ArrayList gats = new ArrayList();
 
        String Text = "e1,e2,e3,e4";
        String output       = Text.replaceAll  ("e1", "AB");
        output                   = output.replaceAll("e2", "AB");
        output                   = output.replaceAll("e3", "ABCD");
        output                   = output.replaceAll("e4", "A");
        output                   = output.replaceAll("e5", "AB");
        output                   = output.replaceAll("e6", "A");
        output                   = output.replaceAll("e7", "B");
        output                   = output.replaceAll("e8", "CEF");
        output                   = output.replaceAll("e9", "CE");
        output                   = output.replaceAll("f1","E");
        output                   = output.replaceAll("f2","F");
        System.out.println(Text + " and " + output);
 
        String[] str = output.split("[\\[\\],\\ ]");
 
        unique.addAll(Arrays.asList(str));
 
        for (int i = 0; i < str.length; i++){
              for (int j = i + 1; j < str.length; j++){
                    char[] chars1 = str[i].toCharArray();
                char[] chars2 = str[j].toCharArray();
                for (char aChars1 : chars1){
                      for (char aChars2 : chars2){
                        if (aChars1 != aChars2){
                              char[] tempc = new char[] { aChars1, aChars2 };
                            Arrays.sort(tempc);
                            unique.add(new String(tempc));
                        }
                    }
                }
            }
        }
        String[] allCombinations = unique.toArray(new String[unique.size()]);
 
        ArrayList<Double> adding = new ArrayList<Double>();
        Map<String, Double> result = new HashMap<String, Double>();
        Map<Character, Double> highestPerLetter = new HashMap<Character, Double>();
 
        for (String segment : allCombinations){
              double sum = 1;
 
            for (int i = 0; i < segment.length(); i++){
                char c = segment.charAt(i);
                String letter = String.valueOf(c);
                double letters = 0.0;
 
                if (letter.equals("A")) {
                    letters = 1.0 / segment.length();
                } else if (letter.equals("B")) {
                    letters = 1.0 / segment.length();
                } else if (letter.equals("C")) {
                    letters = 1.0 / segment.length();
                } else if (letter.equals("D")) {
                    letters = 1.0 / segment.length();
                } else if (letter.equals("E")) {
                    letters = 1.0 / segment.length();
                } else if (letter.equals("F")) {
                    letters = 1.0 / segment.length();
                }
 
                System.out.println(c + "=" + letters);
 
                Double highest = highestPerLetter.get(c);
                if (highest == null) {
                    highestPerLetter.put(c, letters);
                } else {
                    highestPerLetter.put(c, Math.max(highest, letters));
                }
                double total = letters;
 
                adding.add(total);
 
                Double[] ar = adding.toArray(new Double[adding.size()]);
                int a1 = ar.length;
                sum *= ar[a1 - 1];
            }
 
            System.out.println("The Sum of " + segment + " is: " + sum + "\n");
            result.put(segment, sum);
        }
 
        List<String> sortedKeys = Arrays.asList((String[]) result.keySet().toArray(new String[result.keySet().size()]));
        Collections.sort(sortedKeys);
       

 
        try {
 
            PrintWriter out = new PrintWriter(new FileWriter("results1.csv"));
            for (int i = 0, count = sortedKeys.size(); i < count; i++) {
                String key = sortedKeys.get(i);
                System.out.println(key + " " + result.get(key));
                out.println(result.get(key) + "," + key);
            }
 
 
            System.out.println("\nHighest Per Letter: " + highestPerLetter);
            out.close();
        } catch (IOException ioexception) {
            ioexception.printStackTrace();
        }
       
        String[] onedArray = output.split(",");
        String[][] letters = new String[onedArray.length][];
       
        for(int i=0;i<onedArray.length;i++){
              char[] ch = onedArray[i].trim().toCharArray();
              letters[i] = new String[ch.length];
              for (int j=0; j<ch.length; j++)
              letters[i][j] = new String(ch, j, 1);
            }
            
            Pattern p = Pattern.compile("(.)(?=\\1)");
            Set set = new HashSet<String>();
            set.add("");
       
        for( int s=0; s<letters.length; s++ ){
              Set set2 = new HashSet<String>();
              Iterator it = set.iterator();
              
              int ix=0;
              
              while (it.hasNext()){
                    Object element = it.next();
                    
                    ix++;
                    for( int r = 0; r < letters[s].length; r++ ){
                          set2.add(p.matcher(element + letters[s][r]).replaceAll(""));
                                         if (ix++ == set.size() -1){
                                gats.add(element);
                          }

             }
           }
           set=set2;
           System.out.println( );
           System.out.println(s);
           it = set.iterator();
           while (it.hasNext()) {
          System.out.println(it.next());                
               }
                
      }
     
     
     
     System.out.println("\nThe array list");
     
                        for(Object o: gats)
                {
   
                      System.out.println(o);
                }

       
    }
}
Sorry - can you post that in the 'Attach Code Snippet' window

import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;
import java.util.regex.*;
 
public class gats_v1{
      public static void main(String[] args) {
            Set<String> unique = new HashSet<String>();
            ArrayList gats = new ArrayList();
 
        String Text = "e1,e2,e3,e4";
        String output       = Text.replaceAll  ("e1", "AB");
        output                   = output.replaceAll("e2", "AB");
        output                   = output.replaceAll("e3", "ABCD");
        output                   = output.replaceAll("e4", "A");
        output                   = output.replaceAll("e5", "AB");
        output                   = output.replaceAll("e6", "A");
        output                   = output.replaceAll("e7", "B");
        output                   = output.replaceAll("e8", "CEF");
        output                   = output.replaceAll("e9", "CE");
        output                   = output.replaceAll("f1","E");
        output                   = output.replaceAll("f2","F");
        System.out.println(Text + " and " + output);
 
        String[] str = output.split("[\\[\\],\\ ]");
 
        unique.addAll(Arrays.asList(str));
 
        for (int i = 0; i < str.length; i++){
              for (int j = i + 1; j < str.length; j++){
                    char[] chars1 = str[i].toCharArray();
                char[] chars2 = str[j].toCharArray();
                for (char aChars1 : chars1){
                      for (char aChars2 : chars2){
                        if (aChars1 != aChars2){
                              char[] tempc = new char[] { aChars1, aChars2 };
                            Arrays.sort(tempc);
                            unique.add(new String(tempc));
                        }
                    }
                }
            }
        }
        String[] allCombinations = unique.toArray(new String[unique.size()]);
 
        ArrayList<Double> adding = new ArrayList<Double>();
        Map<String, Double> result = new HashMap<String, Double>();
        Map<Character, Double> highestPerLetter = new HashMap<Character, Double>();
 
        for (String segment : allCombinations){
              double sum = 1;
 
            for (int i = 0; i < segment.length(); i++){
                char c = segment.charAt(i);
                String letter = String.valueOf(c);
                double letters = 0.0;
 
                if (letter.equals("A")) {
                    letters = 1.0 / segment.length();
                } else if (letter.equals("B")) {
                    letters = 1.0 / segment.length();
                } else if (letter.equals("C")) {
                    letters = 1.0 / segment.length();
                } else if (letter.equals("D")) {
                    letters = 1.0 / segment.length();
                } else if (letter.equals("E")) {
                    letters = 1.0 / segment.length();
                } else if (letter.equals("F")) {
                    letters = 1.0 / segment.length();
                }
 
                System.out.println(c + "=" + letters);
 
                Double highest = highestPerLetter.get(c);
                if (highest == null) {
                    highestPerLetter.put(c, letters);
                } else {
                    highestPerLetter.put(c, Math.max(highest, letters));
                }
                double total = letters;
 
                adding.add(total);
 
                Double[] ar = adding.toArray(new Double[adding.size()]);
                int a1 = ar.length;
                sum *= ar[a1 - 1];
            }
 
            System.out.println("The Sum of " + segment + " is: " + sum + "\n");
            result.put(segment, sum);
        }
 
        List<String> sortedKeys = Arrays.asList((String[]) result.keySet().toArray(new String[result.keySet().size()]));
        Collections.sort(sortedKeys);
        
 
 
        try {
 
            PrintWriter out = new PrintWriter(new FileWriter("results1.csv"));
            for (int i = 0, count = sortedKeys.size(); i < count; i++) {
                String key = sortedKeys.get(i);
                System.out.println(key + " " + result.get(key));
                out.println(result.get(key) + "," + key);
            }
 
 
            System.out.println("\nHighest Per Letter: " + highestPerLetter);
            out.close();
        } catch (IOException ioexception) {
            ioexception.printStackTrace();
        }
        
        String[] onedArray = output.split(",");
        String[][] letters = new String[onedArray.length][];
        
        for(int i=0;i<onedArray.length;i++){
              char[] ch = onedArray[i].trim().toCharArray();
              letters[i] = new String[ch.length];
              for (int j=0; j<ch.length; j++)
              letters[i][j] = new String(ch, j, 1);
            }
            
            Pattern p = Pattern.compile("(.)(?=\\1)");
            Set set = new HashSet<String>();
            set.add("");
        
        for( int s=0; s<letters.length; s++ ){
              Set set2 = new HashSet<String>();
              Iterator it = set.iterator();
              
              int ix=0;
              
              while (it.hasNext()){
                    Object element = it.next();
                    
                    ix++;
                    for( int r = 0; r < letters[s].length; r++ ){
                          set2.add(p.matcher(element + letters[s][r]).replaceAll(""));
                                         if (ix++ == set.size() -1){
                                gats.add(element);
                          } 
 
             }
           }
           set=set2;
           System.out.println( );
           System.out.println(s);
           it = set.iterator();
           while (it.hasNext()) {
          System.out.println(it.next());                
               }
                
      } 
      
      
      
     System.out.println("\nThe array list");
      
                        for(Object o: gats)
                {
    
                      System.out.println(o);
                }
 
       
    }
}

Open in new window

If you just want the third one, try changing

>>                     if (ix++ == (set.size() - 1)) {

to

                     if (ix == 3) {
I have tried that but it is still not storing the third iteration as I want to store the following in the arraylist:
ABCA
ABA
BDA
BADA
A
BABA
ACA
BA
BACA
ADA
ABDA
BCA

But it is storing the following:
B
B
B
B
BC
Oops sorry

>>   if (ix == 3) {

should have been

   if (ix == 2) {
tried that aswell...but it stores the following:

The array list
B
B
A
A
A
A
AB
Well that may be the case, but it's doing what you asked me to show you how to do. That suggests to me that the question 'how do i store the third iteration?' is the wrong question...
if i am correct then the third iteration is this (and this is what I am trying to store in the arraylist):
ABCA
ABA
BDA
BADA
A
BABA
ACA
BA
BACA
ADA
ABDA
BCA
>>if i am correct then the third iteration is this

That might be what you're trying to store, but you'll probably find it isn't the third iteration
In fact, there may be no third iteration. Add the following just before you add to the list and tell me what it prints:
ok I see that they may not be a third iteration, however I can only add the following to the array list once the iterator has generated it.
ABCA
ABA
BDA
BADA
A
BABA
ACA
BA
BACA
ADA
ABDA
BCA
CEHJ, I have just worked it out  that Set set2 = new HashSet<String>(); will output the above list which I need...sorry for the all the bother and thanks for your help. However can I store this set in an array or arraylist...is it even possible?
ASKER CERTIFIED SOLUTION
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
Create an account to see this answer
Signing up is free. No credit card required.
Create Account
yes the set does give me the correct output...how can i store the values of the set in array?
is it like this?

objectArray = set.toArray();
array = (MyClass[])set.toArray(new MyClass[set.size()]);
List sets = new ArrayList(set); I have converted the set into an arraylist...seems to the trick now :-)
:-)