Reputation: 167
I have a string array that has duplicate value, then I remove the duplicate. Now, I need to get the array key from the result before and store it to new int array. I do not know how it will work in Java, since I search java doesn't provide array keys. Could anybody help, please?
This is my code for example:
static String[] temp2=new String[arraysimpanloop.size()];
static String[] temp2B4Remove=new String[temp2];
Result temp2 before removing duplication:
temp2 =[1, 1, 3, 3, 3, 3, 3, 3]; index of array=[0, 1, 2, 3, 4, 5, 6, 7];
Result temp2 after removing duplication:
temp2 =[1, 3]; index of array=[0, 2];
My point is, I need to get the array key (index of array) like before removing the duplication. Is it possible in java?
Upvotes: 2
Views: 9335
Reputation: 5709
So, you want to return the indexes of first occurrences of distinct items?
Maps can be really cool for these things, and in this case, all you want to actually remember is when was the first occurrence of each distinct element.
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class DistinctValues {
public static List<Integer> distinctIndexes(String[] strings) {
// holds the mapping { string => index of first occurence of that string }
Map<String, Integer> firstOccurenceMap = new HashMap<String, Integer>();
// do a scan through all the items
for (int i = 0; i < strings.length; i++) {
// store the index position of a string only if you haven't encountered it before
firstOccurenceMap.putIfAbsent(strings[i], i);
}
return new ArrayList<Integer>(firstOccurenceMap.values());
}
public static void main(String[] args) {
String[] strings = new String[] { "1", "1", "3", "3", "3", "3", "3", "3" };
System.out.println(distinctIndexes(strings));
}
}
The output:
[0, 2]
Upvotes: 1
Reputation: 31300
This is a simple way of doing it:
String[] temp2 = new String[]{"1", "1", "3", "1", "3" };
List<String> values = new ArrayList<>();
List<Integer> indices = new ArrayList<>();
for( int i = 0; i < temp2.length; ++i ){
String s = temp2[i];
if( ! values.contains( s ) ){
values.add( s );
indices.add( i );
}
}
You can now create arrays from the Lists:
String[] uniq = values.toArray(new String[values.size()]);
Integer[] inds = indices.toArray(new Integer[indices.size()]);
Upvotes: 1