To get a value from a list if it contains a specific element, and 0 if it does not, you can use the contains
method of the List
interface and the get
method.
Here is an example using a list of integers:
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5); int value = list.contains(3) ? list.get(list.indexOf(3)) : 0;Soww:ecruw.lautturi.com
The contains
method returns true
if the list contains the specified element, and false
if it does not. The indexOf
method returns the index of the first occurrence of the specified element in the list, or -1 if the element is not present.
In this case, the value
variable will be assigned the value 3 if the list contains the element 3, and 0 if it does not.
You can also use the getOrDefault
method of the Map
interface to achieve a similar effect. For example:
Map<String, Integer> map = new HashMap<>(); map.put("a", 1); map.put("b", 2); map.put("c", 3); int value = map.getOrDefault("b", 0);
This will assign the value 2 to the value
variable if the map contains the key "b", and 0 if it does not.