Java list element exists

Check if element of list exists java

Solution 2: Ok so based on your answer, we have no choice but to check each element of C against A and B. But since A and B are in ascending order, performance should be reasonable: Solution 3: This is a more efficient version using ArrayLists: Solution 1: you can use method contains description: Solution 2: implements the interface, which defines the method. If the current number is greater than the biggest number in the A,B ranges (B[topRangeIndex]), return the current answer counter because no further element from C (sorted) could be in the A,B ranges again.

How to check a list to see if an element exists or not? [duplicate]

Change the contains expression:

List messageCodes = this.getEmailValidationCode( eSignatureInTO ); if( messageCodes.contains( "ES01" ) ) < IESignatureIntegrationOutDto eSignatureOutTO = getEsignService().resendDocuments( eSignatureInTO ); eSignatureInTO.setResendDocs( eSignatureOutTO.isResendDocs() ); >else if( messageCodes.contains( "EE01" ) ) < emailValidationMessage = UiIntegrationKeyConstants.EMAIL_FORMAT_ERROR_MESSAGE; >else if( !Collections.disjoint(messageCodes,Arrays.asList( "ES02", "ES03", "ES04", "EE02", "EE03", "EE04" ) ) ) < emailValidationMessage = UiIntegrationKeyConstants.EMAIL_VALIDATION_ERROR_MESSAGE; >else

The Collections.disjoint acts as a «contains any» comparison. This way if one or more of the error codes exists, it will go into the if clause.

So if the the code is ES03 or ES04 or any one of them I want to populate the emailValidationMessage variable but it doesn’t do it.

Shouldn’t you be doing something like :

if( messageCodes.contains("ES03") || messageCodes.contains("ES04"))

In the second if, you’re asking if there’s a list stored inside your String array. That won’t work. You should do a .contains for each of the individual values you’re looking for.

Читайте также:  Php text to svg

Java — How can I can check if a value exists in an, «Here 66 existed in list but return false» No. Your list contains only one element, and it’s that ugly concatenated string you created before. 66 is not an element in your list. But even given that, your logic will still return true, as per my previous comment. –

Finding if the element exist in a given range

If the input ranges are already ordered from smallest to largest (B[i]

int bottomRangeIndex = 0; int topRangeIndex = numberOfABRangesYouHave - 1; int answerCounter = 0; C.sort(); // Sort C so that it goes from smallest to largest number. for number in C: < if (number < A[bottomRangeIndex]) < continue; >else if (number > B[topRangeIndex]) < return answerCounter; >else < while ((number >B[bottomRangeIndex++]) && (bottomRangeIndex if (bottomRangeIndex > topRangeIndex) < return answerCounter; >else < answerCounter++; bottomRangeIndex++; >> > 

This might have some bug that I am not thinking of, but basically what this does is:

  1. Sorts C. I know you say you can’t do this, but I fail to see why unless it’s a homework problem.
  2. Skips checking anything in the A,B ranges if the number from C falls completely outside of those ranges. If the current number is greater than the biggest number in the A,B ranges (B[topRangeIndex]), return the current answer counter because no further element from C (sorted) could be in the A,B ranges again.
  3. Since C is sorted and the current number is greater than the bottom element in all A,B ranges, starts checking if the number in C falls inside the B end of each A range. The number being checked is always the smallest element in C, so if it fails to fall within the B end of an A range, that A,B range should never be checked again so the bottomRangeIndex is incremented.
  4. If every range has been eliminated by the while loop, we are done checking (the current element in C is greater than the biggest number in any A,B range, we do not need to check anything else.
  5. If the number in C being checked was NOT greater than a number at the end of an A,B range (located at bottomRangeIndex), that A,B range contained an element from C. We increment the answer counter, move the bottomRangeIndex up, and continue.

Try this and see if it works. If this is homework and you really can’t sort C, then you can modify this to give you the right answer with a small amount of tweaking, but I won’t say how.

Ok so based on your answer, we have no choice but to check each element of C against A and B. But since A and B are in ascending order, performance should be reasonable:

 int len = A.length; boolean[] eliminated = new boolean[len]; // initially all elements are false int totalEliminated = 0; for (int i = 0; i < C.length; i++) < int c = C[i]; for (int j = 0; j < len && A[j] = c && !eliminated[j]) < System.out.println(c + " eliminates " + A[j] + " - " + B[j]); eliminated[j] = true; if (++totalEliminated == len) < return i+1; >> > > return 0; 

This is a more efficient version using ArrayLists:

 int len = arrA.length; ArrayList A = new ArrayList(len); ArrayList B = new ArrayList(len); for (int i=0; i for (int i = 0; i < C.length; i++) < int c = C[i]; int j = 0; while (j= c) < A.remove(j); if (A.isEmpty()) return i+1; B.remove(j); >else < j++; >> > return 0; 

Check if an element of an array exists in another array, (JAVA) The user should be able to enter a colour and then the program should check if the inputted colour is inside the array or not. Check if an element of an array exists in another array (JAVA) Ask Question Asked 6 years, 6 months ago. Modified 6 years, 6 months ago. Viewed 10k times

How do I check if an element exists in a queue ( LinkedList ) before adding it?

you can use contains(Object o) method

Returns true if this list contains the specified element. More formally, returns true if and only if this list contains at least one element e such that (o==null ? e==null : o.equals(e)). [. ]

Parameters: o – element whose presence in this list is to be tested

Returns: true if this list contains the specified element

LinkedList implements the Collection interface, which defines the Collection#contains method.

You can do what you’re after with any class that derives from Collection easily by just using the contains method.

See the docs on LinkedList#contains for more information.

Note: It uses Objects#equals to determine if the item is in the Collection .

If you have the same reference, I think you’ll be good. If you have different references representing the same data, then you may need to @Override the equals method on your object.

package com.example.Solution; import java.util.LinkedList; import java.util.Queue; public class Sol < public static void main(String[] args)< Queueq1= new LinkedList<>(); q1.add(new Address("abc",1,"url1")); Address a1=new Address("abc",1,"url"); if(!q1.contains(a1)) q1.add(a1); Address a2=new Address("abc",2,"url"); if(!q1.contains(a2)) < q1.add(a2); >Address a3=new Address("abc",1,"url2"); if(!q1.contains(a3)) < q1.add(a3); >System.out.println(q1.size()); > > class Address < String name; int id; String url; public Address(String name, int id, String url) < this.name = name; this.id = id; this.url = url; >public String getName() < return name; >public void setName(String name) < this.name = name; >public int getId() < return id; >public void setId(int id) < this.id = id; >public String getUrl() < return url; >public void setUrl(String url) < this.url = url; >public boolean equals(Object o1) < Address address=(Address) o1; return address.getId()==this.id; >> 

Java — Check if element of linked list exists, Check if element of linked list exists. Ask Question Asked 8 years, 8 months ago. Modified 3 years, 3 months ago. Viewed 27k times Inefficient for large lists in Java. No tail recursion. – duffymo. Dec 2, 2013 at 15:16. Avoid recursions when you can. You can, avoid it. – Maroun.

Источник

Check existence of an element in Java ArrayList

The java.util.ArrayList.contains() method can be used to check if an element exists in an ArrayList or not. This method has a single parameter i.e. the element whose presence in the ArrayList is tested. Also it returns true if the element is present in the ArrayList and false if the element is not present.

A program that demonstrates this is given as follows

Example

import java.util.ArrayList; import java.util.List; public class Demo < public static void main(String[] args) < List aList = new ArrayList(); aList.add("A"); aList.add("B"); aList.add("C"); aList.add("D"); aList.add("E"); System.out.println("The element C is available in ArrayList? " + aList.contains("C")); System.out.println("The element Z is available in ArrayList? " + aList.contains("Z")); >>

Output

The output of the above program is as follows

The element C is available in ArrayList? true The element Z is available in ArrayList? false

Now let us understand the above program.

The ArrayList aList is created. Then ArrayList.add() is used to add the elements to the ArrayList. ArrayList.contains() is used to check if “C” and “Z” are available in the ArrayList and the result is displayed. A code snippet which demonstrates this is as follows

List aList = new ArrayList(); aList.add("A"); aList.add("B"); aList.add("C"); aList.add("D"); aList.add("E"); System.out.println("The element C is available in ArrayList? " + aList.contains("C")); System.out.println("The element Z is available in ArrayList? " + aList.contains("Z"));

Источник

Check if Element exists in a Collection using Lambda Expressions

sneppets-java8

If you wanted to check whether element exists in a collection or not using specific id or name, the better approach is to use anyMatch() method of Stream interface of Lambda Expressions.

Lambda Expressions – Check if Element exists in a Collection

The example below shows how to use anyMatch() method to check whether any elements of the stream match the provided predicate. The predicate will not be evaluated if the stream is empty.

public class Skill < private String name; private Long id; public Skill() < >public Skill(Long id, String name) < this.id = id; this.name = name; >public String getName() < return name; >public void setName(String name) < this.name = name; >public Long getId() < return id; >public void setId(Long id) < this.id = id; >>

Example – Lambda Expression

package com.sneppets.app; import java.util.ArrayList; import java.util.List; import com.sneppets.domain.Skill; public class LambdaExample < public static void main (String[] args) < ListskillList = new ArrayList<>(); Skill skill1 = new Skill(1L, "Java"); skillList.add(skill1); Skill skill2 = new Skill(2L, "Python"); skillList.add(skill2); Skill skill3 = new Skill(3L, "Golang"); skillList.add(skill3); String skill1Name = "C"; boolean cExists = skillList.stream().anyMatch(s -> s.getName().equals(skill1Name)); System.out.println("C skill exists in collection ? : " + cExists); String skill2Name = "Java"; boolean jExists = skillList.stream().anyMatch(s -> s.getName().equals(skill2Name)); System.out.println("Java skill exists in collection ? : " + jExists); > >
C skill exists in collection ? : false Java skill exists in collection ? : true

java.util.Stream Notes

  • A stream is not a data structure that stores elements, but it just takes the elements from a source, for example an array.
  • Any operation that you perform on stream produces a result without modifying its source.
  • It is unbounded unlike collections.
  • The elements of stream are visited only once during the life of stream.

Advantages of Lambda Expressions

  • Conciseness
  • Readability
  • Reduction in code inflate.
  • Code reuse.
  • Functional Programming – programming using expressions.

Further Learning

References

Источник

Оцените статью