Check array list and remove some arguments [duplicate] - java

This question already has answers here:
Iterating through a Collection, avoiding ConcurrentModificationException when removing objects in a loop
(31 answers)
Closed 10 years ago.
I have array list of strings. I want to check in specific moment if in this array I have more elements than my "i", if yes I want to remove that elements. For example. I have five elements in array. I choose element which index is four. I want to check if exist higher element(in this case that higher will be element which index is 5) and remove that element. If I choose 3 element I want to remove 4 and 5 element. I do something like that:
for(int j = 0; j<descriptions.size();j++){
if(!descriptions.get(i+1).isEmpty()){
descriptions.remove(i+1);
}
}
This solution work good when I choose 3 element and two elements was removed. But when I want choose 4 element I get index out of bound exception. How I can solve my problem?

I don't quite see the point of using for loop in your code.
What you probably want to do is to remove any items beyond i th element in the list.
The easiest way to do is to repeatedly remove the last element from the list.
Here's a sample code for reference:
while(descriptions.size() > i){
descriptions.remove(descriptions.size()-1);
}

public static void main(String[] args) {
//list of string with 5 elements
List<String> descriptions = new ArrayList<String>();
descriptions.add("first");
descriptions.add("second");
descriptions.add("third");
descriptions.add("4");
descriptions.add("5");
//the size you want to check for the list
int i = 3;
int howMuchToRemove = descriptions.size()-i;
//if the list how more object from > i , we will remove objects from it
if (howMuchToRemove > 0)
for (int j=0 ; j < howMuchToRemove ; j++)
//remove the last object in the list
descriptions.remove(descriptions.size()-1);
System.out.println(descriptions.toString());
}

I have five elements in array. I choose element which index is four.
The fifth element is at index 4. if you want to choose the 4th element, it's index will be 3.
Modify your code as following:
int size = descriptions.size();
for(int j = size -1; j>choosenNum; j--)
{
descriptions.remove(j);
}

public static void main(String[] args) {
ArrayList<String> list = new ArrayList<String>();
list.add("a");
list.add("a");
list.add("a");
list.add("a");
list.add("a");
indexToRemove(list, 5);
}
private static void indexToRemove(ArrayList<String> list, int index) {
if (list.size() > index) {
list.remove(index);
System.out.println(index + "th item removed");
} else
System.out.println("Can't remove");
}
You mean a function which will remove the given index element? then try this.

for(int i = descriptions.size()-1; i > indexToDeleteAfter; i--){
descriptions.remove(i);
}
Or, defer to ArrayList:
if(descriptions.size() - 1 > indexToDeleteAfter)
{
descriptions.removeRange(indexToDeleteAfter + 1, descriptions.size() - 1);
}
http://docs.oracle.com/javase/1.4.2/docs/api/java/util/ArrayList.html#removeRange(int,%20int)

Related

Arraylist java.lang.IndexOutOfBoundsException: Index 3 out of bounds for length 3 Error

I created a method which takes an Arraylist of string and an integer. It's going to remove all string whose length is less than the given integer.
For example:
Arraylist = ["abcde", "aabb", "aaabbb", "abc", "ab"]
integer = 4
So the new Arraylist should be: ["abcde", "aabb", "aaabbb"]
But I'm getting this error message:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 3 out of bounds for length 3
Here is my code:
public static void main(String[] args){
ArrayList<String> newArrayList = new ArrayList<>();
newArrayList.add("string1");
newArrayList.add("string2");
newArrayList.add("rem");
newArrayList.add("dontremove");
removeElement(newArrayList, 4); // new arraylist must be = [string1, string2, dontremove]
}
public static void removeElement(ArrayList<String> arraylist, int inputLen){
int arrayLen = arraylist.size();
for(int i=0; i<arrayLen; i++){
if(arraylist.get(i).length() < inputLen){
arraylist.remove(i);
i--;
}
}
System.out.println("New Arraylist: " + arraylist);
}
What's wrong with this code?
You're looping from 0 to the size of the array which is 4. Inside the loop you're removing items so the size of the array becomes less than 4, so you get this exception.
Try looping like this:
Iterator<String> iterator = arraylist.iterator();
while (iterator.hasNext()) {
String word = iterator.next();
if (word.length() < inputLen) {
iterator.remove();
}
}
You're modifying the list while iterating over its indexes. Once you remove the first item, the list will be shorter than you expect, and you'll get this error once you reach the index of the original last element. Luckily, the removeIf method can do the heavy lifting for you:
public static void removeElement(List<String> arraylist, int inputLen) {
arraylist.removeIf(s -> s.length() < inputLen);
System.out.println("New Arraylist: " + arraylist);
}
The length of the array should change when you remove elements. The arrayLen variable stores the length of the array, but doesn't change when the array's length shrinks. To change it, you should be able to just replace arrayLen with arrayList.size(), which will change when your remove elements
int arrayLen = arraylist.size();
The problem is that your index has a value of 4.
But then as soon as you remove an item from the list you now only have 3 entries.
So in your loop when you try to access the the 4th entry you will now get an IndexOutOfBounds error.
The solution is to start at the end of the ArrayList and count down to 0.
For (int i = arrayLen - 1; i >= 0; i--)
and inside the loop you don't need the:
i--;

Why do elements inside a List modify themselves? [duplicate]

This question already has answers here:
After ArrayList.add() in a loop, all elements are identical. Why? [duplicate]
(3 answers)
Closed 2 years ago.
I want to get different array elements combinations (permutations) of an array to a List. I swap the first and the last element of the array through a for loop and the combination (permutation) is added to the List. Then the second and the element before the last is swapped and added to the List, so and so forth. Suppose the array is arr[1,2,3,4,5,6,7], the first element added to the List would be arr[7,2,3,4,5,6,1]. The second element would be arr[7,6,3,4,5,2,1]. But what I end up getting is something like arr[7,6,5,4,3,2,1] for all the elements in the List.
The problem is that the elements added to the List are also modified correspondingly with the current modification of the array. I end up getting similar array elements in the List. What I want is different permutations or arrays with different combinations of elements. Can you please help me with this?
private List<Gate[]> generateSolutions(Gate[] solution) {
List<Gate[]> sList= new ArrayList<>();
int i, j;
for (i = 0, j = solution.length - 1; i < solution.length / 2; i++, j--) {
Gate temp;
temp = solution[i];
solution[i] = solution[j];
solution[j] = temp;
sList.add(solution);
}
return sList;
}
import java.util.ArrayList;
import java.util.List;
/**
* Dev Parzival
* Date : 27/10/2020 Time : 22:40
* I have a confidence about my life that comes from standing tall on my own two feet.
*/
public class Permutation {
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<>(10);
//Make sure that the list has unique numbers
for(int i=0;i<3;i++)
list.add(i+1);
int n =list.size();
Permutation permutation = new Permutation();
//Generater permutation
permutation.permute(list, 0, n-1);
}
private void permute(ArrayList<Integer> list, int l, int r) {
//When l is equal to one less than the length of the list we will display it.
if (l == r)
System.out.println(list);
else{
//The l valuse specifies which position we want to fix
for (int i = l; i <= r; i++) {
//After diciding the position we fix it by swapping it.
swap(list,l,i);
//Here we are fixing l+1 th number
permute(list, l+1, r);
//Swapping it back to its original position so initial order is maintained
swap(list,l,i);
}
}
}
//Swap function will swap ith and jth numbers of the list
private void swap(List<Integer> list, int i, int j) {
int temp=list.get(i);
list.set(i,list.get(j));
list.set(j,temp);
}
}
Above code is used for generating permutation.

Dividing a Java List into sublists based on values

Here's my list:
myList =
["HEADING","POST","POST","POST","CALL_TO_ACTION","HEADING","POST","POST","POST","CALL_TO_ACTION","HEADING","POST","POST","CALL_TO_ACTION"]
I would like to have some logic in place that would help me divide myList into below three sub-lists (stored as, say, List<List<String> subLists):
["HEADING","POST","POST","POST","CALL_TO_ACTION"]
["HEADING","POST","POST","POST","CALL_TO_ACTION"]
["HEADING","POST","POST","CALL_TO_ACTION"]
Please note, the number three comes from the number of occurrences of the element "HEADING" (which I could find out using Collections.frequency(myList, "HEADING")).
One way to do this is,
Step 1: Collect all the indices from your myList where "HEADING" appears.
List<Integer> indexList = new ArrayList<>();
for(int index = 0; index < list.size(); index++) {
if(list.get(index).equals("HEADING"))
indexList.add(index);
}
Step 2: Iterate through this indexList and create sub lists by using current index and the next index.
for(int builderIndex = 0; builderIndex < indexList.size(); builderIndex++) {
List<String> test = null;
if(builderIndex == indexList.size() - 1) {
test = list.subList(indexList.get(builderIndex), list.size());
} else {
test = list.subList(indexList.get(builderIndex), indexList.get(builderIndex + 1));
}
System.out.println(test);
}
Boundary condition is to check if the current index is equal to one less than the size of the indexList. If yes, then the end index of the sub list would be the size of the original list.
I hope this helps.

Reversing and combining a list

I have the following list:
list 1= 1,2,3,4,5,6
I am trying to make a list that contains the following:
list c= 1,6,2,5,3,4
However, I cannot figure out how to do it. I know how to iterate through 6 but I don't know how to get to the last number and iterate backwards. I know a ListIterator can be used to go backwards but I still cannot figure it out.
This is what I did to add the original, I just don't understand how to iterate backwards:
public static void q(Set<String>list1)
{
Set<String>combined = new HashSet();
Iterator<String> forward = list1.iterator();
Iterator <String> backwards = list1.iterator();
for (int i=0; i<list1.size(); i++)
{
combined.add(forward.next());
//code to go backwards
}
}
This isn't to solve your problem, but rather to show you how ListIterator can be used to go backwards since you couldn't figure it out.
List<Integer> list = new ArrayList<>();
for (int n = 1; n <= 6; n++) { // Add 1, 2, ... 6 to list
list.add(n);
}
ListIterator it = list.listIterator(list.size());
while (it.hasPrevious()) {
System.out.println(it.previous());
}
The listIterator method of a List allows you to specify the index to start at as a parameter.
The hasPrevious method of the ListIterator checks if there is a previous element (self-explanitory).
The previous() method of the ListIterator returns the previous element in the list and moves the cursor position backwards.
Using ListIterator you can go forwards and backwards as you please using next() and previous() respectively.
Alternatively, using a for statement instead of using ListIterator...
for (int i = list.size() - 1; i >= 0; i--) {
System.out.println(list.get(i));
}
I am not sure if you really wanted a Set given you were talking about lists. This is the idea without explicitly using list iterators however they would behave the similarly.
How to use a list iterator: http://www.java2s.com/Tutorial/Java/0140__Collections/ListIteratorInreverseorder.htm
public static List<Integer> interleaveFrontBack(List<Integer> list) {
if (list.size() <= 2){
return new LinkedList<Integer>(list);
}
List interleaved = new LinkedList<Integer>();
int end = list.size() - 1;
int front = 0;
while (end > front){
interleaved.add(list.get(front++));
interleaved.add(list.get(end--));
}
// if odd sized list need to add last element
if (end == front){
interleaved.add(list.get(front));
}
return interleaved;
}
Simple Algo would be
1.) just use two positions , i =0 for increment and j = size-1 for decrements
2.) add elements to new list using i and j positions while traversing to the middle of the content list
Integer []aa=new Integer[]{1,2,3,4,5,6};
List<Integer> list =Arrays.asList(aa);
int n=list.size();
List<Integer> list2 =new ArrayList<>();
for (int i = 0,j=list.size()-1; i <n/2 ; i++,j--) {
list2.add(list.get(i));
list2.add(list.get(j));
}
// if(n%2!=0) list2.add(list.get(n/2)); // un-comment this , to handle
// odd list size too ,dynamism
list2.forEach(i->System.err.print(i+" "));
Output:
1 6 2 5 3 4
Assuming that you simply want to put the last element of the first list on the second index, you can do something like:
List<Integer> input = Arrays.asList(1, 2, 3, 4, 5, 6);
// create new list that initially contains first and last element of input list
List<Integer> output = new ArrayList<>(Arrays.asList(input.get(0), input.get(input.size()-1)));
// now iterate the "in between" input elements and add them to output
for (int i=1; i < input.size() -1 ; i++) {
output.add(input.get(i));
}
System.out.println("in: " + input);
System.out.println("out: " + output);
Of course, the above is just one way of doing this; there are many others
Not sure what your exactly looking for and where your code has broke. You could try:
List<Integer> intergers = new ArrayList<>();
for(int i = 1; i < 7; i++) {
if(i < 6) {
intergers.add((i-1), i);
} else {
intergers.add(1, i); //when i is 6 place it in the second index
}
}
System.out.println("List: " + intergers.toString());
With java list you can chose the index and if that index has a value the value well be pushed to the next index. It was the simplest thing I could think of. This is what it printed out:
List: [1, 6, 2, 3, 4, 5]

Arraylist swap elements [duplicate]

This question already has answers here:
How to change value of ArrayList element in java
(7 answers)
Closed 8 years ago.
How do I swap the the first and last elements of an ArrayList?
I know how to swap the elements of an array: setting a temporary value to store the first element, letting the first element equal the last element, then letting the last element equal the stored first element.
int a = values[0];
int n = values.length;
values[0] = values[n-1];
values[n-1] = a;
So for an ArrayList<String> would it be like this?
String a = words.get(0);
int n = words.size();
words.get(0) = words.get(n-1);
words.get(n-1) = a
You can use Collections.swap(List<?> list, int i, int j);
In Java, you cannot set a value in ArrayList by assigning to it, there's a set() method to call:
String a = words.get(0);
words.set(0, words.get(words.size() - 1));
words.set(words.size() - 1, a)
Use like this. Here is the online compilation of the code. Take a look http://ideone.com/MJJwtc
public static void swap(List list,
int i,
int j)
Swaps the elements at the specified positions in the specified list. (If the specified positions are equal, invoking this method leaves the list unchanged.)
Parameters:
list - The list in which to swap elements.
i - the index of one element to be swapped.
j - the index of the other element to be swapped.
Read The official Docs of collection
http://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#swap%28java.util.List,%20int,%20int%29
import java.util.*;
import java.lang.*;
class Main {
public static void main(String[] args) throws java.lang.Exception
{
//create an ArrayList object
ArrayList words = new ArrayList();
//Add elements to Arraylist
words.add("A");
words.add("B");
words.add("C");
words.add("D");
words.add("E");
System.out.println("Before swaping, ArrayList contains : " + words);
/*
To swap elements of Java ArrayList use,
static void swap(List list, int firstElement, int secondElement)
method of Collections class. Where firstElement is the index of first
element to be swapped and secondElement is the index of the second element
to be swapped.
If the specified positions are equal, list remains unchanged.
Please note that, this method can throw IndexOutOfBoundsException if
any of the index values is not in range. */
Collections.swap(words, 0, words.size() - 1);
System.out.println("After swaping, ArrayList contains : " + words);
}
}
Oneline compilation example http://ideone.com/MJJwtc
for (int i = 0; i < list.size(); i++) {
if (i < list.size() - 1) {
if (list.get(i) > list.get(i + 1)) {
int j = list.get(i);
list.remove(i);
list.add(i, list.get(i));
list.remove(i + 1);
list.add(j);
i = -1;
}
}
}

Categories

Resources