I would like to iterate through two dimensional ArrayList which includes String objects using iterator. I also would like to iterate in a way that let me choose whether I want to iterate horizontally(row) first or vertically(column) by using a boolean value. How can I implement this in java?
What I've tried so far.
public class IterateThis implements Iterator<String>{
ArrayList<ArrayList<String>> array;
public IterateThis(){
array = new ArrayList<ArrayList<String>>();
array.add(new ArrayList<String>());
array.add(new ArrayList<String>());
array.add(new ArrayList<String>());
array.get(0).add("1");
array.get(0).add("2");
array.get(0).add("2");
array.get(1).add("4");
array.get(1).add("5");
array.get(1).add("6");
}
Iterator<String> it = array.iterator(); //This gives me an error...why?
I don't know how I can implement the boolean value though.
Maybe you need to implement two versions, with a boolean that decides which loop to use:
public void iterate(boolean horizantalFirst){
if(horizontalFirst){
for(int i=0; i<array.size(); i++){ // first iterate through the "outer list"
for(int j=0; j<array.get(i).size(); j++){ // then iterate through all the "inner lists"
array.get(i).get(j)="1";
}
}
}else{
int j=0; // index to iterate through the "inner lists"
for(; j<array.get(j).size(); j++){ //dangerous, you need to be sure that there is a j-th element in array
for(int i=0; i<array.size(); i++){ // iterate here through the outer list, by always working on the j-th element
array.get(i).get(j)="1";
}
}
}
}
Why not try this:
import java.util.ArrayList;
public class Iteration
{
private ArrayList<ArrayList<String>> array;
public Iteration()
{
array = new ArrayList<>();
array.add(new ArrayList<String>());
array.get(0).add("000");
array.get(0).add("001");
array.get(0).add("010");
array.add(new ArrayList<String>());
array.get(1).add("100");
array.get(1).add("101");
array.get(1).add("110");
array.get(1).add("111");
iterateRowWise();
System.out.println("\n\n");
iterateColumnWise();
}
public void iterateRowWise()
{
// This uses iterator behind the scene.
for (ArrayList<String> row : array)
{
for (String element : row)
{
System.out.print(element + " ");
}
System.out.println();
}
}
public void iterateColumnWise()
{
int arraySize = array.size();
int maxColumns = getMaximumListSize();
for (int c = 0; c < maxColumns; c++)
{
for (int r = 0; r < arraySize; r++)
{
ArrayList<String> rowList = array.get(r);
if (c < rowList.size())
{
System.out.print(rowList.get(c) + " ");
}
}
System.out.println();
}
}
private int getMaximumListSize()
{
int maxListSize = 0;
for (ArrayList<String> rowList : array)
{
if (maxListSize < rowList.size())
maxListSize = rowList.size();
}
return maxListSize;
}
public static void main(String[] args)
{
new Iteration();
}
}
The iterateRowWise() method iterates using the iterator, but it does so behind the scene.
The iterateColumnWise() method doesn't use iterator, but its safe to use.
Row-wise iteration is simple as shown in the #Awfully Awesome answer.
Tried a columnwise iteration with assumption that List will always have m cross n elements where m=n
public static void IterateThis() {
ArrayList<ArrayList<String>> array = new ArrayList<ArrayList<String>>();
array.add(new ArrayList<String>());
array.add(new ArrayList<String>());
array.get(0).add("1");
array.get(0).add("2");
array.get(0).add("2");
array.get(1).add("4");
array.get(1).add("5");
array.get(1).add("6");
Iterator<ArrayList<String>> it = array.iterator();
int topLevelIteratorResetCounter = 0;
int noOfIteratorNextRequired = 1;
int size = array.size();
while (it.hasNext()) {
ArrayList<String> strList = it.next();
if (noOfIteratorNextRequired > strList.size())
break;
Iterator<String> itString = strList.iterator();
int numtimes = 0;
String str = null;
while (numtimes != noOfIteratorNextRequired) {
str = itString.next();
numtimes++;
}
System.out.println(str);
numtimes = 0;
topLevelIteratorResetCounter++;
if (topLevelIteratorResetCounter == size) { //as column count is equal to column size
it = array.iterator(); //reset the iterator
noOfIteratorNextRequired++;
topLevelIteratorResetCounter = 0;
}
}
}
The answer uses Iterator.
Related
I trying to make Iterator of List<HashSet<Integer>> list = new ArrayList<>().
However, I keep falling.
This is What I tried Iterator Iterator<HashSet<Integer>> iterator = new list.iterator()
Please somebody help me :(
How can I create iterator of that collection?
It's part of the code
public class Test {
private static List<HashSet<Integer>> basketList = new ArrayList<>();
private static Map<Integer, Integer> map = new HashMap<>();
public static void settingBasket(String fname) throws FileNotFoundException {
Scanner scan = new Scanner(new File(fname));
int n = Integer.parseInt(scan.next());
Iterator<HashSet<Integer>> iter = basketList.iterator(); // error
for(int i=0; i<n; i++) {
scan.next();
int m = Integer.parseInt(scan.next());
HashSet<Integer> elems = new HashSet<>();
for(int j=0; j<m; j++)
elems.add(Integer.parseInt(scan.next()));
basketList.add(elems);
}
}
public static void settingPair() {
int size = basketList.size();
for(int i=0; i<size; i++) {
Iterator<HashSet<Integer>> iter = basketList.iterator(); // error
}
}
You can simply interate over your Sets in your List with a nested loop as below :
for (HashSet<Integer> set : basketList) {
for (Integer i : set) {
System.out.println(i);
}
}
Alternatively, if you want to have an Iterator for each Set in your list, you can do it as below :
for (int i = 0 ; i < basketList.size(); i++) {
Iterator<Integer> iter = basketList.get(i).iterator();
...
}
Or :
for (HashSet<Integer> set : basketList) {
Iterator<Integer> iter = set.iterator();
...
}
Can you try this? You can make it simple by using iterator method.
HashSet<Integer> set1 = new HashSet<>(Arrays.asList(1, 2));
HashSet<Integer> set2 = new HashSet<>(Arrays.asList(3, 4));
List<HashSet<Integer>> list = new ArrayList<>(Arrays.asList(set1, set2));
// make iterator
Iterator<HashSet<Integer>> iterator = list.iterator();
while(iterator.hasNext()) {
// get element(HashSet) in iterator
HashSet<Integer> element = iterator.next();
for (Integer intValue : element) {
// access element in HashSet
System.out.println(intValue);
}
}
UPDATE: You should to get the element from basketList and create an iterator.
like this:
public static void settingPair() {
int size = basketList.size();
for (int i = 0; i < size; i++) {
// get the element from basketList
HashSet<Integer> element = basketList.get(i);
// create iterator
Iterator<Integer> iterator = element.iterator();
}
}
I have to read a paragraph containing words from an input file. then create a doubly linked list containing the distinct words read, where the words of the same length are placed in the same list, in ascending order.
So i tried to create an array of doubly linked list, I know how to add the words but I can't sort them in ascending order.(we have to sort the words while adding them, not sorting the text then adding.)
int x = max(s);
DoublyLinkedList[] list = new DoublyLinkedList[x];
for (int i = 0; i < list.length; i++) {
list[i] = new DoublyLinkedList();
}
public static void m(DoublyLinkedList[] list, String s) {
String[] s1 = s.split(" ");
for (int i = 0; i < s1.length; i++) {
list[s1[i].length()].addLast(s1[i]);
}
}
public static int max(String s) {
String[] s1 = s.split(" ");
int max = s1[1].length();
for (int i = 0; i < s1.length; i++) {
if (s1[i].length() > max) {
max = s1[i].length();
}
}
return max + 1;
}
public static void insertAtRightSpot(DoublyLinekdList list, String s){
int i = 0;
boolean inserted = false;
while(i<list.length()){
if(list.get(i).compareTo(s) < 0){
i++;
} else {
list.insertAt(s, i);
inserted = true;
break;
}
}
if (!inserted) list.addLast(s);
}
Try insertAtRightSpot(list[s1[i].length()], s1[i]) instead of list[s1[i].length()].addLast(s1[i])
The Method searches for the first Element that is not smaller that the one you want to insert and inserts it right before
I would like to create a code that will help me copy elements from the 'allWords' ArrayList to the 'distinctWords'. but his time in the distinct words ArrayList I want a word to appear just one, eliminating redundancy in the "distinctWords' ArrayList.
this is the code that I have come up with and I am getting no output.
import java.util.ArrayList;
public class copyElements {
static ArrayList<String> distinctWords = new ArrayList<String> ();
static ArrayList<String> allWords = new ArrayList<String> ();
static int allWordsCount = 0;
static int distinctWordsCount;
static int tracker;
public static void main(String[] args) {
allWords.add("you");
allWords.add("want");
allWords.add("to");
allWords.add("go");
allWords.add("to");
allWords.add("dubai");
allWords.add("and");
allWords.add("you");
allWords.add("also");
allWords.add("want");
allWords.add("to");
allWords.add("go");
allWords.add("to");
allWords.add("seychelles");
//printing all items in the 'allwords' arraylist
//System.out.println("CONTENTS OF 'ALL WORDS' ARRAYLIST : ");
distinctWords.add(0,allWords.get(0));
distinctWordsCount = 1;
int i = 1;
for(int j = 1; j <= distinctWords.size(); j++){
if(i < allWords.size()){
tracker = 0;
if (tracker == j){
distinctWords.add(j, allWords.get(i));
System.out.println("\t\t\t" + distinctWords.get(j));
distinctWordsCount ++;
i++;
} else
if (tracker != j){
if(allWords.get(i) != distinctWords.get(tracker)){
//distinctWords.add(allWords.get(i));
//distinctWordsCount ++;
tracker++;
}
else
if(allWords.get(i) == distinctWords.get(tracker)){
i++;
}
//System.out.println("CONTENTS OF 'ALL WORDS' ARRAYLIST : ");
//System.out.println("\t\t\t" + distinctWords.get(j));
}
}
//System.out.println("\t\t\t" + distinctWords.get(j));
}
//System.out.println("\n\nTHE NUMBER OF ITEMS IN THE 'ALLWORDS' ARRAYLIST IS : " + allWords.size());
//System.out.println("\n\nTHE NUMBER OF ITEMS IN THE 'DISTINCTWORDS' ARRAYLIST IS : " + allWords.size());
System.out.println("\n\nITEMS IN THE 'DISTINCTWORDS' ARRAYLIST ARE : " + distinctWords.size());
}
}
How about the following code:
for (int i = 0, size = allWords.size(); i < size; i++)
{
String word = allWords.get(i);
// add the word if it is not in distinctWords
if (!distinctWords.contains(word))
{
distinctWords.add(word);
}
}
If you don't care about the order of the words, then you could use a Set as suggested.
Set<String> distinctSet = new HashSet<String>(allWords);
// if you want the set put into your other arrayList
distinctWords.addAll(distinctSet);
//al1 and al2 are ArrayList<Object>
for(Object obj:al1){
if(!al2.contains(obj))
al2.add(obj);
}
I think this can give you a set of all distinct words.
Set<String> distinctWords = new HashSet<>(allWords);
If you do need an array, you can simple do this:
ArrayList<String> distinctWordsArr = new ArrayList<>(distinctWords);
New to java programming and I am currently trying to create a class similar to ArrayList using Arrays.
Am trying to add elements to an array and expand the array by copying them to a new array of bigger size.
I am getting an out of index error at 20.
Code may be messy but currently really stuck.
public class MyArrayList{
private String[] strings;
private int arraySize;
private int storedStrings;
public MyArrayList(int arraySize){
this.arraySize = arraySize;
this.strings = new String[arraySize];
}
public void addString(String string){
storedStrings = 0;
for (int i = 0; i < this.arraySize;i ++){
if (strings[i] != null){
storedStrings = storedStrings +1;
}
}
if (storedStrings == this.arraySize){
String[] newArray = new String[this.arraySize+10];
for (int i = 0; i < this.strings.length; i++){
strings[i] = newArray[i];
}
this.strings = newArray;
newArray[storedStrings] = string;
this.arraySize = this.arraySize +10;
}
else{
strings[storedStrings] = string;
}
for(int i = 0; i < strings.length; i++)
{
//System.out.println(strings[i]);
}
}
}
The code is being run in the test class where the error is being generated on line 10 of test class and line 47 of MyArrayList class.
This is the test code
public class TestArrayList{
public static void main(String[] args)
{
MyArrayList a = new MyArrayList(10);
for (int i = 0; i <50; i++){
a.addString("Test" + i);
}
for (int i = 0; i<50;i++){
System.out.println(a.getString(i*5));
}
}
}
you can do it like this:
public void addString(String string){
if (storedStrings == this.arraySize){
this.arraySize += 10;
String[] newArray = new String[this.arraySize];
for (int i = 0; i < this.storedStrings; i++){
newArray[i] = strings[i];
}
this.strings = newArray;
}
if (strings[storedStrings] == null){
strings[storedStrings++] = string;
}
// remove this loop it will show repeating values otherwise
for(int i = 0; i < storedStrings; i++)
{
System.out.println(strings[i]);
}
}
edit: as you are new to java always think about how can you do more with less code, how to avoid repetition of code, how to merge things that do common task. That will help you write better code
edit2 : the problem is with this loop
for (int i = 0; i<50;i++){
System.out.println(a.getString(i*5));
}
if you have 50 elements in array the getString method on (eg) i = 25 will be 25*5 = 125 which is not the index in the array that's why you are getting ArrayIndexOutOfBound Exception.
you can add
public int size(){
return storedStrings;
}
to check the size of your list which is the maximum item that is inside the list
First with your code there is a mistake in this line
strings[i] = newArray[i];
because you arenĀ“t copying the old data to new array but cleaning the strings array, I suppose that you wish do the contrary action.
In other hand you have extra code that you could improve.
public class MyArrayList{
private String[] strings;
private int arraySize;
public MyArrayList(int arraySize){
this.arraySize = arraySize;
this.strings = new String[arraySize];
}
public void addString(String string){
// Since you always do this
// it's better to use a local variale
int storedStrings = 0;
// Use the foreach syntax
// it's less prone to errors
// and easier to read
for (String s : this.strings){
if (s != null){
storedStrings++;
}else{
// since you want to count the strings in your array
// and you put them in this array
// one after the other
// no need to check the whole array
// when you find null you can exit the loop
break;
}
}
if (storedStrings == this.arraySize){
String[] newArray = new String[this.arraySize+10];
for (int i = 0; i < this.strings.length; i++){
// here we need to copy the content of strings in newArray
// NOT the other way
newArray[i] = this.strings[i];
}
this.strings = newArray;
newArray[storedStrings] = string;
this.arraySize += 10;
}else{
this.strings[storedStrings] = string;
}
}
public String[] getStrings(){
return this.strings;
}
}
As for the test class
public static void main(String[] args){
MyArrayList a = new MyArrayList(10);
for (int i = 0; i <50; i++){
a.addString("Test" + i);
}
for (String s : a.getStrings()){
System.out.println(a);
}
}
public boolean makeReservation(int id, AvilaNatalyPassenger request) {
boolean status = true;
ArrayList<Integer> inputValues = new ArrayList<Integer>();
for (int i = 0; i < 22; i++) {
for (int j = 0; j < 5; j++) {
id = seats[i][j];
if (id != -1) {
if (inputValues.contains(id)) {
status = false;
break;
}
else {
inputValues.add(id);
for(int a = 0; a < inputValues.size; a++)
seats[a] = inputValues[a];
}
}
}
}
return status;
}
This is what I have but its not correct. I need to add what I have in inputVaule arrayList into the array seats.
You can also look at the Java API: http://docs.oracle.com/javase/7/docs/api/index.html?java/util/ArrayList.html
public Object[] toArray()
Returns an array containing all of the elements in this list in proper sequence (from first to last element).
So this is what you could do:
seats[a] = inputValues.toArray();
Furthermore you cannot use inputValues[a] since it is not an array. What you probably could do is
seats[a] = (inputValues.toArray())[a];
To answer your question, here is an example:
ArrayList<String> stock_list = new ArrayList<String>();
stock_list.add("stock1");
stock_list.add("stock2");
String[] stockArr = new String[stock_list.size()];
stockArr = stock_list.toArray(stockArr);
for(String s : stockArr)
System.out.println(s);
Example is taken from here