private static boolean moreThanOnce(ArrayList<Integer> list, int number) {
if (list.contains(number)) {
return true;
}
return false;
}
How do I use list.contains to check if the number was found in the list more than once? I could make a method with for loop, but I want to know if it's possible to do using .contains. Thanks for help!
You can't do it just with contains. That just tests if the item is anywhere in the list.
You can do it with indexOf, though. There are two overloads of indexOf, one of which allows you to set a position in the list to start searching from. So: after you find one, start from one after that position:
int pos = list.indexOf(number);
if (pos < 0) return false;
return list.indexOf(number, pos + 1) >= 0;
Or replace the last line with:
return list.lastIndexOf(number) != pos;
If you want a more concise way (although this iterates the whole list twice in the case that it's not found once):
return list.indexOf(number) != list.lastIndexOf(number);
You can use Streams:
private static boolean moreThanOnce(ArrayList<Integer> list, int number) {
return list.stream()
.filter(i -> i.equals (number))
.limit(2) // this guarantees that you would stop iterating over the
// elements of the Stream once you find more than one element
// equal to number
.count() > 1;
}
If you wish to count how many times it exist in the list
int times = list.stream().filter(e -> number==e).count();
The method add of Set returns a boolean whether a value already exists (true if it does not exist, false if it already exists).
Iterate all the values and try to add it again.
public Set<Integer> findDuplicates(List<Integer> listContainingDuplicates)
{
final Set<Integer> setToReturn = new HashSet<>();
final Set<Integer> set1 = new HashSet<>();
for (Integer yourInt : listContainingDuplicates)
{
if (!set1.add(yourInt))
{
setToReturn.add(yourInt);
}
}
return setToReturn;
}
Others already point out the problem. However, typically you could use the Collection.frequency method:
private static boolean moreThanOnce(ArrayList<Integer> list, int number) {
return Collections.frequency(list, number) > 1;
}
Disclaimer
Other answers are great because they explain the efficient ways to do it but the sole purpose of this solution is to show how List::contains can be used to solve this problem which is the specific requirement of the question. Please also check the following comment from OP requesting for it.
Thank you, do you think it's possible to do with .contains only? The
other user commented "indexOf".
Solution:
It's not possible with List::contains alone but you can combine List::contains with some other functions of List and make it work.
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
// Tests
List<Integer> list = List.of(10, 20, 10, 30);
System.out.println(moreThanOnce(new ArrayList<>(list), 10));
System.out.println(moreThanOnce(new ArrayList<>(list), 20));
}
private static boolean moreThanOnce(List<Integer> list, int number) {
if (list.size() == 1) {
return false;
}
if (list.get(0) == number && list.subList(1, list.size()).contains(number)) {
return true;
}
return moreThanOnce(list.subList(1, list.size()), number);
}
}
Output:
true
false
I have something like List<List<UsersDetails>> userList. If I debug to see its value it's giving [[]] i.e., List<UsersDetails> is empty and List<List<UsersDetails>> is also empty. Is there a way to check if List<UsersDetails> is empty without iteration?
I tried userList.sizeOf, userList.empty() functions and userList==null operator but all are giving false.
If you want to check each element in the "outer" list you have to iterate over it somehow. Java 8's streams would hide this from you, though, and provide a slightly cleaner syntax:
boolean allEmpty = userList.stream().allMatch(l -> l == null || l.empty());
There is not. There is:
if (userList.isEmpty() || userList.get(0).isEmpty()) { ... }
But mostly if the notion: "This a list of lists where the list of lists contains 1 list, but that list is empty" is something you should consider as 'empty', you're using the wrong datastructure. You haven't explained what you are modelling with this List<List<UsersDetails>> but perhaps if you elaborate on that, some other data type in java.* or perhaps guava would be far more suitable. For example, maybe a Map<Integer, UsersDetail> is a better match here (mapping a user's ID to their details).
You could create your own List that simply delegates to e.g. ArrayList but prevents null or empty lists from being added:
public class NonEmptyUserList implements List<List<UserDetails>>{
private ArrayList<List<String>> mDelegate = new ArrayList<>();
public void add(int index, List<UserDetails> element) {
if (element == null || element.isEmpty()) {
return;
}
mDelegate.add(index, element);
}
public boolean add(List<UserDetails> element) {
if (element == null || element.isEmpty()) {
return false;
}
return mDelegate.add(e);
}
public List<UserDetails> set(int index, List<UserDetails> element) {
if (element == null || element.isEmpty()) {
return null;
}
return mDelegate.set(index, element);
}
public boolean addAll(Collection<? extends List<UserDetails>> c) {
boolean changed = false;
for (final List<String> list : c) {
changed = changed || add(list);
}
return changed;
}
public boolean addAll(int index, Collection<? extends List<UserDetails>> c) {
boolean changed = false;
int startIndex = index;
for (final List<String> list : c) {
add(startIndex, list);
changed = changed || (list != null) && !list.isEmpty();
startIndex++;
}
return changed;
}
// delegate all other methods required by `List` to mDelegate
}
Using this list you can be sure no null or empty values will be present and thus you can use:
NonEmptyUserList userList = new NonEmptyUserList();
userList.add(null);
userList.add(Collections.emptyList());
userList.isEmpty(); // returns true
List<UserDetails> subList = new ArrayList<>();
subList.add(null);
userList.add(subList);
userList.isEmpty(); // returns false
If you want to handle sub lists with only null elements as empty as well you will need to extend the above implementation. This is however the only solution I can currently imagine that doesn't involve iterating over the list's elements. But I'd not really recommend this solution. I just wrote it down to show you what might be possible.
I personally think the answer provided by #Mureinik using streams is most favorable.
Not sure how I can achieve this.
I have a object list, where it consists of multiple data example
ABC1231211
ABC1231111
ABC4562222
ABC4562456
Now I trying to seperate the list according to their code, which is 123 and 456, and add header and tailer to them. So my expected result would be
Head
ABC1231211
ABC1231111
Tail
Head2
ABC4562222
ABC4562456
Tail2
But the result I get is
Head
ABC1231211
Tail
Head
ABC1231111
Tail
Head2
ABC4562222
Tail2
Head2
ABC4562456
Tail2
Code
#Override
public List process(List<Detail> l) throws Exception {
for (Detail d : l) {
if (d.Code().equals("123")) {
list = generateS(d);
}
if (d.Code().equals("456")) {
list = generateR(d);
}
}
return list;
}
public List<String> generateS(Detail d) throws Exception {
try {
list.add(new HDR("Head").getHeader());
DetailL x = new DetailL();
x.setType(d.getType());
....
list.add(x.getDetail());
list.add(new TLR("Tail").getTailer());
} catch (Exception ex) {
throw new BatchException(DetailProcessor.class, ex);
}
return list;
}
Any help would be much appreciated
If you're using Java 8, you can use streams:
public void process(List<Detail> details) throws Exception {
Map<String, List<Detail>> byCode =
details.stream().collect(Collectors.groupingBy(Detail::getCode));
byCode.entrySet().stream().forEach(entry -> {
System.out.println(headerFromType(entry.getKey()));
entry.getValue().foreach(System.out::println);
System.out.println(tailFromType(entry.getKey()));
}
with headerFromType and tailFromType returning "Head"/"Head2" or "Tail"/"Tail2", depending on the given type.
You are generating a new head and tail for each element instead of adding to the already-generated list.
For each Detail, you should first check if the list exists, and if it doesn't, then call generateS or generateR as appropriate. If the list exists, you want to call e.g. sList.add(sList.size()-1, d.getDetail()). You'll of course want to replace the call d.getDetail() with the value that's supposed to go into the list or a method call that returns that value.
Then you probably want to use list.addAll(sList) to add the generated lists' contents to list.
Another solution is to generate the combined list on demand, and store the two lists separately. In that case, you would check if the corresponding list is null in the beginning of generateS or generateR, and initialize it if it is.
You create a new header and a new tail every time you call generateS or generateR but you should just create a new header once if you find a new code ( for example 123).
Solution: You collect your details into a list before you call generateS or generateR and put all the details from collected list into your DetailL.
Here is another implemetation that takes another approach:
private void go() {
List<String> list = new ArrayList<>();
list.add("ABC1231211");
list.add("ABC1231111");
list.add("ABC4562222");
list.add("ABC4562456");
String lastTag = null;
int startPos = 0;
for (int i = 0; i < list.size(); i++) {
String tag = list.get(i).substring(3, 6);
if (!tag.equals(lastTag) && lastTag != null) {
print(list.subList(startPos, i));
startPos = i;
}
lastTag = tag;
}
print(list.subList(startPos, list.size()));
}
private void print(List<String> list) {
System.out.println("Head");
for (String item : list) {
System.out.println(item);
}
System.out.println("Tail");
}
Simply "If you come accross an element with a different tag, print the previous sublist". (And print whatever is left at the end since that sublist's printout is not triggered by a new tag.)
I have a String[] with values like so:
public static final String[] VALUES = new String[] {"AB","BC","CD","AE"};
Given String s, is there a good way of testing whether VALUES contains s?
Arrays.asList(yourArray).contains(yourValue)
Warning: this doesn't work for arrays of primitives (see the comments).
Since java-8 you can now use Streams.
String[] values = {"AB","BC","CD","AE"};
boolean contains = Arrays.stream(values).anyMatch("s"::equals);
To check whether an array of int, double or long contains a value use IntStream, DoubleStream or LongStream respectively.
Example
int[] a = {1,2,3,4};
boolean contains = IntStream.of(a).anyMatch(x -> x == 4);
Concise update for Java SE 9
Reference arrays are bad. For this case we are after a set. Since Java SE 9 we have Set.of.
private static final Set<String> VALUES = Set.of(
"AB","BC","CD","AE"
);
"Given String s, is there a good way of testing whether VALUES contains s?"
VALUES.contains(s)
O(1).
The right type, immutable, O(1) and concise. Beautiful.*
Original answer details
Just to clear the code up to start with. We have (corrected):
public static final String[] VALUES = new String[] {"AB","BC","CD","AE"};
This is a mutable static which FindBugs will tell you is very naughty. Do not modify statics and do not allow other code to do so also. At an absolute minimum, the field should be private:
private static final String[] VALUES = new String[] {"AB","BC","CD","AE"};
(Note, you can actually drop the new String[]; bit.)
Reference arrays are still bad and we want a set:
private static final Set<String> VALUES = new HashSet<String>(Arrays.asList(
new String[] {"AB","BC","CD","AE"}
));
(Paranoid people, such as myself, may feel more at ease if this was wrapped in Collections.unmodifiableSet - it could then even be made public.)
(*To be a little more on brand, the collections API is predictably still missing immutable collection types and the syntax is still far too verbose, for my tastes.)
You can use ArrayUtils.contains from Apache Commons Lang
public static boolean contains(Object[] array, Object objectToFind)
Note that this method returns false if the passed array is null.
There are also methods available for primitive arrays of all kinds.
Example:
String[] fieldsToInclude = { "id", "name", "location" };
if ( ArrayUtils.contains( fieldsToInclude, "id" ) ) {
// Do some stuff.
}
Just simply implement it by hand:
public static <T> boolean contains(final T[] array, final T v) {
for (final T e : array)
if (e == v || v != null && v.equals(e))
return true;
return false;
}
Improvement:
The v != null condition is constant inside the method. It always evaluates to the same Boolean value during the method call. So if the input array is big, it is more efficient to evaluate this condition only once, and we can use a simplified/faster condition inside the for loop based on the result. The improved contains() method:
public static <T> boolean contains2(final T[] array, final T v) {
if (v == null) {
for (final T e : array)
if (e == null)
return true;
}
else {
for (final T e : array)
if (e == v || v.equals(e))
return true;
}
return false;
}
Four Different Ways to Check If an Array Contains a Value
Using List:
public static boolean useList(String[] arr, String targetValue) {
return Arrays.asList(arr).contains(targetValue);
}
Using Set:
public static boolean useSet(String[] arr, String targetValue) {
Set<String> set = new HashSet<String>(Arrays.asList(arr));
return set.contains(targetValue);
}
Using a simple loop:
public static boolean useLoop(String[] arr, String targetValue) {
for (String s: arr) {
if (s.equals(targetValue))
return true;
}
return false;
}
Using Arrays.binarySearch():
The code below is wrong, it is listed here for completeness. binarySearch() can ONLY be used on sorted arrays. You will find the result is weird below. This is the best option when array is sorted.
public static boolean binarySearch(String[] arr, String targetValue) {
return Arrays.binarySearch(arr, targetValue) >= 0;
}
Quick Example:
String testValue="test";
String newValueNotInList="newValue";
String[] valueArray = { "this", "is", "java" , "test" };
Arrays.asList(valueArray).contains(testValue); // returns true
Arrays.asList(valueArray).contains(newValueNotInList); // returns false
If the array is not sorted, you will have to iterate over everything and make a call to equals on each.
If the array is sorted, you can do a binary search, there's one in the Arrays class.
Generally speaking, if you are going to do a lot of membership checks, you may want to store everything in a Set, not in an array.
For what it's worth I ran a test comparing the 3 suggestions for speed. I generated random integers, converted them to a String and added them to an array. I then searched for the highest possible number/string, which would be a worst case scenario for the asList().contains().
When using a 10K array size the results were:
Sort & Search : 15
Binary Search : 0
asList.contains : 0
When using a 100K array the results were:
Sort & Search : 156
Binary Search : 0
asList.contains : 32
So if the array is created in sorted order the binary search is the fastest, otherwise the asList().contains would be the way to go. If you have many searches, then it may be worthwhile to sort the array so you can use the binary search. It all depends on your application.
I would think those are the results most people would expect. Here is the test code:
import java.util.*;
public class Test {
public static void main(String args[]) {
long start = 0;
int size = 100000;
String[] strings = new String[size];
Random random = new Random();
for (int i = 0; i < size; i++)
strings[i] = "" + random.nextInt(size);
start = System.currentTimeMillis();
Arrays.sort(strings);
System.out.println(Arrays.binarySearch(strings, "" + (size - 1)));
System.out.println("Sort & Search : "
+ (System.currentTimeMillis() - start));
start = System.currentTimeMillis();
System.out.println(Arrays.binarySearch(strings, "" + (size - 1)));
System.out.println("Search : "
+ (System.currentTimeMillis() - start));
start = System.currentTimeMillis();
System.out.println(Arrays.asList(strings).contains("" + (size - 1)));
System.out.println("Contains : "
+ (System.currentTimeMillis() - start));
}
}
Instead of using the quick array initialisation syntax too, you could just initialise it as a List straight away in a similar manner using the Arrays.asList method, e.g.:
public static final List<String> STRINGS = Arrays.asList("firstString", "secondString" ...., "lastString");
Then you can do (like above):
STRINGS.contains("the string you want to find");
With Java 8 you can create a stream and check if any entries in the stream matches "s":
String[] values = {"AB","BC","CD","AE"};
boolean sInArray = Arrays.stream(values).anyMatch("s"::equals);
Or as a generic method:
public static <T> boolean arrayContains(T[] array, T value) {
return Arrays.stream(array).anyMatch(value::equals);
}
You can use the Arrays class to perform a binary search for the value. If your array is not sorted, you will have to use the sort functions in the same class to sort the array, then search through it.
ObStupidAnswer (but I think there's a lesson in here somewhere):
enum Values {
AB, BC, CD, AE
}
try {
Values.valueOf(s);
return true;
} catch (IllegalArgumentException exc) {
return false;
}
Actually, if you use HashSet<String> as Tom Hawtin proposed you don't need to worry about sorting, and your speed is the same as with binary search on a presorted array, probably even faster.
It all depends on how your code is set up, obviously, but from where I stand, the order would be:
On an unsorted array:
HashSet
asList
sort & binary
On a sorted array:
HashSet
Binary
asList
So either way, HashSet for the win.
Developers often do:
Set<String> set = new HashSet<String>(Arrays.asList(arr));
return set.contains(targetValue);
The above code works, but there is no need to convert a list to set first. Converting a list to a set requires extra time. It can as simple as:
Arrays.asList(arr).contains(targetValue);
or
for (String s : arr) {
if (s.equals(targetValue))
return true;
}
return false;
The first one is more readable than the second one.
If you have the google collections library, Tom's answer can be simplified a lot by using ImmutableSet (http://google-collections.googlecode.com/svn/trunk/javadoc/com/google/common/collect/ImmutableSet.html)
This really removes a lot of clutter from the initialization proposed
private static final Set<String> VALUES = ImmutableSet.of("AB","BC","CD","AE");
In Java 8 use Streams.
List<String> myList =
Arrays.asList("a1", "a2", "b1", "c2", "c1");
myList.stream()
.filter(s -> s.startsWith("c"))
.map(String::toUpperCase)
.sorted()
.forEach(System.out::println);
One possible solution:
import java.util.Arrays;
import java.util.List;
public class ArrayContainsElement {
public static final List<String> VALUES = Arrays.asList("AB", "BC", "CD", "AE");
public static void main(String args[]) {
if (VALUES.contains("AB")) {
System.out.println("Contains");
} else {
System.out.println("Not contains");
}
}
}
Using a simple loop is the most efficient way of doing this.
boolean useLoop(String[] arr, String targetValue) {
for(String s: arr){
if(s.equals(targetValue))
return true;
}
return false;
}
Courtesy to Programcreek
the shortest solution
the array VALUES may contain duplicates
since Java 9
List.of(VALUES).contains(s);
Use the following (the contains() method is ArrayUtils.in() in this code):
ObjectUtils.java
public class ObjectUtils {
/**
* A null safe method to detect if two objects are equal.
* #param object1
* #param object2
* #return true if either both objects are null, or equal, else returns false.
*/
public static boolean equals(Object object1, Object object2) {
return object1 == null ? object2 == null : object1.equals(object2);
}
}
ArrayUtils.java
public class ArrayUtils {
/**
* Find the index of of an object is in given array,
* starting from given inclusive index.
* #param ts Array to be searched in.
* #param t Object to be searched.
* #param start The index from where the search must start.
* #return Index of the given object in the array if it is there, else -1.
*/
public static <T> int indexOf(final T[] ts, final T t, int start) {
for (int i = start; i < ts.length; ++i)
if (ObjectUtils.equals(ts[i], t))
return i;
return -1;
}
/**
* Find the index of of an object is in given array, starting from 0;
* #param ts Array to be searched in.
* #param t Object to be searched.
* #return indexOf(ts, t, 0)
*/
public static <T> int indexOf(final T[] ts, final T t) {
return indexOf(ts, t, 0);
}
/**
* Detect if the given object is in the given array.
* #param ts Array to be searched in.
* #param t Object to be searched.
* #return If indexOf(ts, t) is greater than -1.
*/
public static <T> boolean in(final T[] ts, final T t) {
return indexOf(ts, t) > -1;
}
}
As you can see in the code above, that there are other utility methods ObjectUtils.equals() and ArrayUtils.indexOf(), that were used at other places as well.
For arrays of limited length use the following (as given by camickr). This is slow for repeated checks, especially for longer arrays (linear search).
Arrays.asList(...).contains(...)
For fast performance if you repeatedly check against a larger set of elements
An array is the wrong structure. Use a TreeSet and add each element to it. It sorts elements and has a fast exist() method (binary search).
If the elements implement Comparable & you want the TreeSet sorted accordingly:
ElementClass.compareTo() method must be compatable with ElementClass.equals(): see Triads not showing up to fight? (Java Set missing an item)
TreeSet myElements = new TreeSet();
// Do this for each element (implementing *Comparable*)
myElements.add(nextElement);
// *Alternatively*, if an array is forceably provided from other code:
myElements.addAll(Arrays.asList(myArray));
Otherwise, use your own Comparator:
class MyComparator implements Comparator<ElementClass> {
int compareTo(ElementClass element1; ElementClass element2) {
// Your comparison of elements
// Should be consistent with object equality
}
boolean equals(Object otherComparator) {
// Your equality of comparators
}
}
// construct TreeSet with the comparator
TreeSet myElements = new TreeSet(new MyComparator());
// Do this for each element (implementing *Comparable*)
myElements.add(nextElement);
The payoff: check existence of some element:
// Fast binary search through sorted elements (performance ~ log(size)):
boolean containsElement = myElements.exists(someElement);
If you don't want it to be case sensitive
Arrays.stream(VALUES).anyMatch(s::equalsIgnoreCase);
Try this:
ArrayList<Integer> arrlist = new ArrayList<Integer>(8);
// use add() method to add elements in the list
arrlist.add(20);
arrlist.add(25);
arrlist.add(10);
arrlist.add(15);
boolean retval = arrlist.contains(10);
if (retval == true) {
System.out.println("10 is contained in the list");
}
else {
System.out.println("10 is not contained in the list");
}
Check this
String[] VALUES = new String[]{"AB", "BC", "CD", "AE"};
String s;
for (int i = 0; i < VALUES.length; i++) {
if (VALUES[i].equals(s)) {
// do your stuff
} else {
//do your stuff
}
}
Arrays.asList() -> then calling the contains() method will always work, but a search algorithm is much better since you don't need to create a lightweight list wrapper around the array, which is what Arrays.asList() does.
public boolean findString(String[] strings, String desired){
for (String str : strings){
if (desired.equals(str)) {
return true;
}
}
return false; //if we get here… there is no desired String, return false.
}
Use below -
String[] values = {"AB","BC","CD","AE"};
String s = "A";
boolean contains = Arrays.stream(values).anyMatch(v -> v.contains(s));
Use Array.BinarySearch(array,obj) for finding the given object in array or not.
Example:
if (Array.BinarySearch(str, i) > -1)` → true --exists
false --not exists
Try using Java 8 predicate test method
Here is a full example of it.
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
public class Test {
public static final List<String> VALUES =
Arrays.asList("AA", "AB", "BC", "CD", "AE");
public static void main(String args[]) {
Predicate<String> containsLetterA = VALUES -> VALUES.contains("AB");
for (String i : VALUES) {
System.out.println(containsLetterA.test(i));
}
}
}
http://mytechnologythought.blogspot.com/2019/10/java-8-predicate-test-method-example.html
https://github.com/VipulGulhane1/java8/blob/master/Test.java
Create a boolean initially set to false. Run a loop to check every value in the array and compare to the value you are checking against. If you ever get a match, set boolean to true and stop the looping. Then assert that the boolean is true.
As I'm dealing with low level Java using primitive types byte and byte[], the best so far I got is from bytes-java https://github.com/patrickfav/bytes-java seems a fine piece of work
You can check it by two methods
A) By converting the array into string and then check the required string by .contains method
String a = Arrays.toString(VALUES);
System.out.println(a.contains("AB"));
System.out.println(a.contains("BC"));
System.out.println(a.contains("CD"));
System.out.println(a.contains("AE"));
B) This is a more efficent method
Scanner s = new Scanner(System.in);
String u = s.next();
boolean d = true;
for (int i = 0; i < VAL.length; i++) {
if (VAL[i].equals(u) == d)
System.out.println(VAL[i] + " " + u + VAL[i].equals(u));
}
How can I remove specific object from ArrayList?
Suppose I have a class as below:
import java.util.ArrayList;
public class ArrayTest {
int i;
public static void main(String args[]){
ArrayList<ArrayTest> test=new ArrayList<ArrayTest>();
ArrayTest obj;
obj=new ArrayTest(1);
test.add(obj);
obj=new ArrayTest(2);
test.add(obj);
obj=new ArrayTest(3);
test.add(obj);
}
public ArrayTest(int i){
this.i=i;
}
}
How can I remove object with new ArrayTest(1) from my ArrayList<ArrayList>
ArrayList removes objects based on the equals(Object obj) method. So you should implement properly this method. Something like:
public boolean equals(Object obj) {
if (obj == null) return false;
if (obj == this) return true;
if (!(obj instanceof ArrayTest)) return false;
ArrayTest o = (ArrayTest) obj;
return o.i == this.i;
}
Or
public boolean equals(Object obj) {
if (obj instanceof ArrayTest) {
ArrayTest o = (ArrayTest) obj;
return o.i == this.i;
}
return false;
}
If you are using Java 8 or above:
test.removeIf(t -> t.i == 1);
Java 8 has a removeIf method in the collection interface. For the ArrayList, it has an advanced implementation (order of n).
In general an object can be removed in two ways from an ArrayList (or generally any List), by index (remove(int)) and by object (remove(Object)).
In this particular scenario: Add an equals(Object) method to your ArrayTest class. That will allow ArrayList.remove(Object) to identify the correct object.
For removing the particular object from arrayList there are two ways. Call the function of arrayList.
Removing on the basis of the object.
arrayList.remove(object);
This will remove your object but in most cases when arrayList contains the items of UserDefined DataTypes, this method does not give you the correct result. It works fine only for Primitive DataTypes. Because user want to remove the item on the basis of object field value and that can not be compared by remove function automatically.
Removing on the basis of specified index position of arrayList. The best way to remove any item or object from arrayList. First, find the index of the item which you want to remove. Then call this arrayList method, this method removes the item on index basis. And it will give the correct result.
arrayList.remove(index);
Here is full example. we have to use
Iterator's remove() method
import java.util.ArrayList;
import java.util.Iterator;
public class ArrayTest {
int i;
public static void main(String args[]) {
ArrayList<ArrayTest> test = new ArrayList<ArrayTest>();
ArrayTest obj;
obj = new ArrayTest(1);
test.add(obj);
obj = new ArrayTest(2);
test.add(obj);
obj = new ArrayTest(3);
test.add(obj);
System.out.println("Before removing size is " + test.size() + " And Element are : " + test);
Iterator<ArrayTest> itr = test.iterator();
while (itr.hasNext()) {
ArrayTest number = itr.next();
if (number.i == 1) {
itr.remove();
}
}
System.out.println("After removing size is " + test.size() + " And Element are :" + test);
}
public ArrayTest(int i) {
this.i = i;
}
#Override
public String toString() {
return "ArrayTest [i=" + i + "]";
}
}
use this code
test.remove(test.indexOf(obj));
test is your ArrayList and obj is the Object, first you find the index of obj in ArrayList and then you remove it from the ArrayList.
AValchev is right.
A quicker solution would be to parse all elements and compare by an unique property.
String property = "property to delete";
for(int j = 0; j < i.size(); j++)
{
Student obj = i.get(j);
if(obj.getProperty().equals(property)){
//found, delete.
i.remove(j);
break;
}
}
THis is a quick solution. You'd better implement object comparison for larger projects.
If you want to remove multiple objects that are matching to the property try this.
I have used following code to remove element from object array it helped me.
In general an object can be removed in two ways from an ArrayList (or generally any List), by index (remove(int)) and by object (remove(Object)).
some time for you arrayList.remove(index)or arrayList.remove(obj.get(index)) using these lines may not work try to use following code.
for (Iterator<DetailInbox> iter = detailInboxArray.iterator(); iter.hasNext(); ) {
DetailInbox element = iter.next();
if (element.isSelected()) {
iter.remove();
}
}
I have tried this and it works for me:
ArrayList<cartItem> cartItems= new ArrayList<>();
//filling the cartItems
cartItem ci=new cartItem(itemcode,itemQuantity);//the one I want to remove
Iterator<cartItem> itr =cartItems.iterator();
while (itr.hasNext()){
cartItem ci_itr=itr.next();
if (ci_itr.getClass() == ci.getClass()){
itr.remove();
return;
}
}
ArrayTest obj=new ArrayTest(1);
test.add(obj);
ArrayTest obj1=new ArrayTest(2);
test.add(obj1);
ArrayTest obj2=new ArrayTest(3);
test.add(obj2);
test.remove(object of ArrayTest);
you can specify how you control each object.
You can use Collections.binarySearch to find the element, then call remove on the returned index.
See the documentation for Collections.binarySearch here:
http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Collections.html#binarySearch%28java.util.List,%20java.lang.Object%29
This would require the ArrayTest object to have .equals implemented though. You would also need to call Collections.sort to sort the list. Finally, ArrayTest would have to implement the Comparable interface, so that binarySearch would run correctly.
This is the "proper" way to do it in Java. If you are just looking to solve the problem in a quick and dirty fashion, then you can just iterate over the elements and remove the one with the attribute you are looking for.
This helped me:
card temperaryCardFour = theDeck.get(theDeck.size() - 1);
theDeck.remove(temperaryCardFour);
instead of
theDeck.remove(numberNeededRemoved);
I got a removal conformation on the first snippet of code and an un removal conformation on the second.
Try switching your code with the first snippet I think that is your problem.
Nathan Nelson
simple use remove() function. and pass object as param u want to remove.
ur arraylist.remove(obj)
or you can use java 8 lambda
test.removeIf(i -> i==2);
it will simply remove all object that meet the condition
Below one is used when removed ArrayTest(1) from test ArrayList
test.removeIf(
(intValue) -> {
boolean remove = false;
remove = (intValue == 1);
if (remove) {
//Success
}
return remove;
});
Example within a simple String List, if anyone wants :
public ArrayList<String> listAfterRemoved(ArrayList<String> arrayList, String toRemove) {
for (int i = 0; i < arrayList.size(); i++) {
if (arrayList.get(i).equals(toRemove)) {
arrayList.remove(toRemove);
}
}
return arrayList;
}
And the call is :
ArrayList<String> arrayList = new ArrayList<>();
arrayList.add("1");
arrayList.add("2");
arrayList.add("3");
arrayList.add("4");
System.out.println("Array List before: " + arrayList.toString());
arrayList = listAfterRemoved(arrayList, "2");
System.out.println("Array List after : " + arrayList.toString());
If you want to remove or filter specific object from ArrayList, there are many ways that you can use it as given below:
Suppose list is the reference variable of arrayList.
List<Student> list = ...;// Stored the objects here
If you know the specific Student object that you want to delete then you can use it simply:
list.remove(student) //if you know the student object
If you know the specific id or name of that student, in that case, use java 8 Collection.removeIf():
list.removeIf(fandom -> id == fandom.getId());
Another way that you can use that is Collectors.partitioningBy:
Map<Boolean, List<Student>> studentsElements = list
.stream()
.collect(Collectors.partitioningBy((Student st) ->
!name.equals(st.getName())));
// All Students who do have not that specific name
List<Student> matching = studentsElements.get(true));
// All Student who has only that specific name
List<Student> nonMatching = studentsElements.get(false));
Or you can simply filter that specific Object
List<Student> studentsElements = list
.stream()
.filter(e -> !name.equals(st.getName()))
.collect(Collectors.toList());