Java - How to get item index from an array with its value? - java

If I have a array list say a string array, then how can I get index of an element with its value?
Code exammple:
private static final String[] TEST = new String[]{
"abc","bcd","def"
}
require its index with something like:
int i = TEST.getPosition("abc");/TEST.indexof(...);//not available
Also I tried with creating ArrayAdapter.
Is there anything like this? Or maybe I need to assign it with that adapter or something?
Or,
How can I get such index of an element?

Simplest idea:
Convert array to list and you can get position of an element.
List<String> abcd = Arrays.asList(yourArray);
int i = abcd.indexOf("abcd");
Other solution, you can iterator array:
int position = 0;
for (String obj : yourArray) {
if (obj.equals("abcd") {
return position;
}
position += 1;
}
//OR
for (int i = 0; i < yourArray.length; i++) {
if (obj.equals("abcd") {
return i;
}
}

You can refer to this question and use the Java 8 Lambda filter function.
Optional<String> optional = Arrays.stream(presents)
.filter(x -> "MyString".equals(x.getName()))
.findFirst();
if(optional.isPresent()) {//Check whether optional has element you are looking for
String s = optional.get();//get it from optional
}
the filter function take a lambda callback and will returns a list with only the values that match the condition in the lambda. In our case, we also want only the first one. That's why are add the findFirst() which will returns only the first value.
The function will returns an Optional, we can check if it contains a value using options.isPresent(). The optional.get() will returns the value.
Replace the "MyString" by your value and it should work.
If you wish to find an index, you can use the indexOf() function after changing your static array to an list : Arrays.asList(array);

There can be two methods which you can opt for -
1) First, as it is an array, you can simply run a for loop and compare using equals() and find the position.
2) Secondly, convert it into an List<> and run indexOf() and find the position.
NOTE: When you convert an array to List, it become a backed version List, it is fixed and size can't be alter --> but it is perfectly fine in your case as your array is final.
List<String> str = Arrays.asList(TEST);
int pos = str.indexOf("abc");

As others have said, the simplest method is Arrays.asList(TEST).indexOf("abc"). But here's an alternative using streams:
int index = IntStream.range(0, TEST.length)
.filter(i -> TEST[i].equals("abc"))
.findFirst()
.orElse(-1);

Related

Java with ArrayLists the index of function

is there a way with the index of function to return the index of a value that is part of a class like just one field of the bigger structure.. I got a simple contact class and I want to return the index when the id is a certain value .. should I be using a different structure than an arrayList it is doing most of what I want but the index of function is frustrating
I think the easiest way is to just iterate over the array, and check the condition with "if". That will be O(n).
You can use the Predicate method explained here.
Optional<Integer> indexOfMatch = IntStream.range(0, yourList.size())
.filter(i -> valueYouAreLookingFor.equals(yourList.get(i).getFieldYouAreChecking()))
.findFirst();
Or if the field holds a primitive value:
Optional<Integer> indexOfMatch = IntStream.range(0, yourList.size())
.filter(i -> valueYouAreLookingFor == yourList.get(i).getFieldYouAreChecking())
.findFirst();
If there is an element in the list that matches your predicate, indexOfMatch will have the index of that element. If not, indexOfMatch will be an empty Optional.
Regarding whether an ArrayList is the appropriate structure, generally if you are working with a list of values, an implementation of List is what you want. Whether it should be ArrayList or some other implementation depends on details of what you are doing with the list. For small list sizes, it often doesn't really matter which implementation you use.
well I switched to a vector from an array list but it did not really help but I did use a loop and the list size and just put the contact in a container each time so I could do my comparison it was kinda messy but I got the index that way.
static int SearchForContact(String ContactID) {
int temp = -1;
Contact searchCon;
for (int z = 0 ; z < contactVector.size(); z++)
{searchCon = contactVector.get(z);
if(searchCon.getId() == ContactID)
{temp = z;}
}
if (temp == -1) {
throw new IllegalArgumentException("Contact not found");
}
return temp;
}
I am iterating over the ArrayList and seeing whether the current value is the id value you want.
int yourValue = 25; //I am assuming it to be an int of value 25, you can keep it whatever you want.
for (int i = 0; i < yourArrayList.size(); i++)
{
if (yourArrayList.get(i) == yourValue)
{
return i; //returning the index value
}
}
return null; //this will run if the value doesn't exist.
Obviously, this would need to be inside a method that returns an integer that is the index. Above, yourArrayList is the ArrayList you are using, and yourValue is the value you need to find. It doesn't have to be an int.

How to filter array with conditions array

I have 2 arrays. In 1 array I have virtual machines with properties. In the other array I have property values. I want to iterate over the 1st array and filter out the elements with the property values from the 2nd array. But when I start to filter it, the following happens:
I start the iteration of the 1st array. For every element of the first array I iterate over every element in the second and I compare the values, but it doesn't work, because it is taking the values from the 2nd array consequentially and I need them with logical and (&&).
for (VirtualMachine vm: VmArray) {
listOfVirtualMachinesToBuild.forEach(
vmFilter-> {
if (vmFilter.getType().equals(vm.getType())) {
Optional<DslModel.DiscoverIf[]> discoverIfOptional =
Optional.ofNullable(vmFilter.getDiscoverIf());
if (discoverIfOptional.isPresent())
for (int i = 0; i < vmFilter.getDiscoverIf().length; i++) {
if (vm.getProperty(
vmFilter.getDiscoverIf()[i].getCondition())
.equals(vmFilter.getDiscoverIf()[i].getValue())) {
specificEntitiesToBuild.add(vm);
}
}
} else {
specificEntitiesToBuild.add(vm);
}
}
});
}
Do you have any ideas how?
You can use the Stream API. I will demonstrate with Strings but the same will work for any class:
String[] strings = {"a", "b", "c"};
Stream<String> stream = Arrays.stream(strings);
String[] filtered = stream.filter(s -> s.equals("a")).toArray(String[]::new);
If you want to check if a String is contained in a String[] (to lookup "properties"), as I think your intention is, you can do:
public boolean propertyExists(String property) {
return Arrays.stream(propertyArray).anyMatch(s -> s.equals(property));
}
It is slightly unclear what you are asking, so this is my best guess. If you edit your question to show your actual code, it will be easier to help.

If only one element in a hashset, how can I get it out?

I have a set like below:
HashSet<Integer> set = new HashSet<Integer>();
set.add(1);
How can I get the 1 out? I can do it by for(integer i : set). My specified problem is "Given an array of integers, every element appears twice except for one. Find that single one."
I want to use add elements into the set if the set doesn't contain it and remove existing elements during the loop. And the last remaining element is the answer. I don't know how to return it.
public static int singleNumber(int[] A) {
HashSet<Integer> set = new HashSet<>();
for (int a : A) {
if (!set.contains(a)) {
set.add(a);
} else {
set.remove(a);
}
}
/**
* for(Integer i : set) { return i; }
*return A[0]; //need one useless return
/**
* while(set.iterator().hasNext()) { return set.iterator().next(); }
* return A[0]; //need one useless return
*/
return set.toArray(new Integer[1])[0];
}
set.iterator().next()
Do so only if you are sure there is an element in the set. Otherwise next() will throw an exception.
Simply try using HashSet#toArray() method
HashSet<Integer> set = new HashSet<Integer>();
set.add(1);
if (set.size() == 1) { // make sure that there is only one element in set
Integer value = set.toArray(new Integer[1])[0];
System.out.println(value);//output 1
}
The typical solution includes a check if the current iterator position has any left element through setIterator.hasNext() which returns true only if there is an extra element unchecked. For example
HashSet set = new HashSet();
Iterator setIterator = set.iterator();
while(setIterator.hasNext()){
String item = setIterator().next();
...
}
If you know what the element is and you just want to empty the set, you can use remove(Object o) (or clear() for that matter). If you don't know what it is and want to see it without removing it, use an iterator. If you don't know what it is and want to remove it, you should use an iterator using the iterator's remove() method. This is the safe (and recommended) way to remove elements from a collection. Since Set is unordered, it's difficult to specify what you want to remove. And for any collection, you would usually only know what you are removing if you iterate through the collection.
Solution Using Java Stream
If you want to use Java Stream any of the following options will give you the desired result:
Option 1
Just return the only element from the stream:
set.stream().findFirst().get()
Option 2
Or use Stream.reduce; since adding the only element to zero has no effect
(a little too much IMHO :))
set.stream().reduce(0, Integer::sum)
You can test it here.

Java ArrayList not working on characters in my case

I have a big doubt. I want to find the first char of a string here which isn't repeated.For e.g. for the input below should return 'c'. So this is how I was planning on doing it. But I noticed the remove method is looking to remove at an index of 98 vs removing the object "a". How do I force it to remove the object "a" instead of removing from index ?
Why doesn't this work ?
And what can I do to change this ?
Is ArrayList always guaranteed to store things in order ?
public void findStartingLetter()
{
String[] array={"a","b","c","d","b","a","d","d","d"};
List<Character> list = new ArrayList<Character>();
for(String i:array)
{
if(list.contains(i.charAt(0)))
list.remove(i.charAt(0));
else
list.add(i.charAt(0));
}
}
EDIT:
Performance wise is this an O(n) function ?
You have to cast manually to a Character since the char gets casted to an int, which in turn goes by index and not value.
list.remove((Character) i.charAt(0));
Will ensure that it is done properly.
Is ArrayList always guaranteed to store things in order ?
Depends on your definition of order:
If you mean the order you add them, Yes.
If you mean numerical/alphabetical order, then No, but you can sort it by using
Collections.sort(list)
This will sort by the natural ascending order of the objects in the list.
I'm not entirely sure why you want to use a List for this, but I would instead recommend a Set - it's guaranteed to not contain duplicates.
Here's the first approach, with a set:
public Set<Character> addToSet(String[] elements) {
Set<Character> res = new HashSet<>();
for(String c : elements) {
res.add(c.charAt(0));
}
return res;
}
Now, if you really want to do this with a List, then it's similar code - you just need to check to see if the element exists before you add it in.
public List<Character> addUnique(String[] elements) {
List<Character> res = new ArrayList<>();
for(String item : elements) {
Character c = item.charAt(0);
if(!res.contains(c)) {
res.add(c);
}
}
return res;
}
Your approach to this problem is quite confusing and you ask many questions which do not seem to relate to your problem.
Why not just use:
String testString = "abcdbaddd";
Character retVal = null;
for (int i = 0; i < testString.length() -1; i++) {
if (testString.charAt(i) == testString.charAt(i + 1)) {
retVal = testString.charAt(i);
break;
}
}
return retVal;
That gets you the first non-repeated character (I'm assuming that by repeated you mean repeated and adjacent) or null if no such character exists.

Getting Index of an item in an arraylist;

I have a Class called AuctionItem. The AuctionItem Class has a method called getName() that returns a String. If I have an ArrayList of type AuctionItem, what is the best way to return the index of an item in the ArrayList that has a specific name?
I know that there is an .indexOf() function. The parameter for this function is an object. To find the item that has a name, should I just use a for loop, and when the item is found, return the element position in the ArrayList?
Is there a better way?
I think a for-loop should be a valid solution :
public int getIndexByname(String pName)
{
for(AuctionItem _item : *yourArray*)
{
if(_item.getName().equals(pName))
return *yourarray*.indexOf(_item)
}
return -1;
}
Yes.you have to loop it
public int getIndex(String itemName)
{
for (int i = 0; i < arraylist.size(); i++)
{
AuctionItem auction = arraylist.get(i);
if (itemName.equals(auction.getname()))
{
return i;
}
}
return -1;
}
Basically you need to look up ArrayList element based on name getName. Two approaches to this problem:
1- Don't use ArrayList, Use HashMap<String,AutionItem> where String would be name
2- Use getName to generate index and use index based addition into array list list.add(int index, E element). One way to generate index from name would be to use its hashCode and modulo by ArrayList current size (something similar what is used inside HashMap)
.indexOf() works well.
If you want an example here is one:
ArrayList<String> example = new ArrayList<String>();
example.add("AB");
example.add("CD");
example.add("EF");
example.add("GH");
example.add("IJ");
example.add("KL");
example.add("MN");
System.out.println("Index of 'AB': "+example.indexOf("AB"));
System.out.println("Index of 'KL': "+example.indexOf("KL"));
System.out.println("Index of 'AA': "+example.indexOf("AA"));
System.out.println("Index of 'EF': "+example.indexOf("EF"));
will give you an output of
Index of 'AB': 0
Index of 'KL': 5
Index of 'AA': -1
Index of 'EF': 2
Note: This method returns -1 if the specified element is not present in the list.
for (int i = 0; i < list.length; i++) {
if (list.get(i) .getName().equalsIgnoreCase("myName")) {
System.out.println(i);
break;
}
}
To find the item that has a name, should I just use a for loop, and when the item is found, return the element position in the ArrayList?
Yes to the loop (either using indexes or an Iterator). On the return value, either return its index, or the item iteself, depending on your needs. ArrayList doesn't have an indexOf(Object target, Comparator compare)` or similar. Now that Java is getting lambda expressions (in Java 8, ~March 2014), I expect we'll see APIs get methods that accept lambdas for things like this.
You could implement hashCode/equals of your AuctionItem so that two of them are equal if they have the same name. When you do this you can use the methods indexOf and contains of the ArrayList like this: arrayList.indexOf(new AuctionItem("The name")). Or when you assume in the equals method that a String is passed: arrayList.indexOf("The name"). But that's not the best design.
But I would also prefer using a HashMap to map the name to the item.
Rather than a brute force loop through the list (eg 1 to 10000), rather use an iterative search approach :
The List needs to be sorted by the element to be tested.
Start search at the middle element size()/2 eg 5000
if search item greater than element at 5000, then test the element at the midpoint between the upper(10000) and midpoint(5000) - 7500
keep doing this until you reach the match (or use a brute force loop through once you get down to a smaller range (eg 20 items)
You can search a list of 10000 in around 13 to 14 tests, rather than potentially 9999 tests.

Categories

Resources