I have a list of point coordinate and want to iterate through a 2D list then process the elements in the hash function to generate the key for my hashtable. I am a bit struggling to iterate through the List> points, also how to pass coordinate (x,y) as value for to the hashtable (key,value)?
public static List<List<Integer>> myMethod(int k, List<List<Integer>> points){
Hashtable pt = new Hashtable();
for (int i = 0; i <points.size(); i++)
{
for (int j = 0; j < points.get(i).size(); j++)
{
Integer x = points.get(i);
Integer y = points.get(j);
pt.put(hashfunction( x, y), points.get(i));
}
}
//return list of pairs ;
}
You should be able to help yourself by using some data structures that more accurately reflect your data. If you have point-data, consider using Pair
, then your List
of points is actually that!
Next, all the Map
structures within Java
will calculate their own hash values, you don't need to do that! You will need to calculate your desired keys though. From your snippet, it isn't clear why you want the Hashtable/Map
at all - it is a local variable that is never read and will garbage collected right after the method executes. Thus, I guessed that you wanted to return that. If so you can do:
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.apache.commons.lang3.tuple.Pair;
import com.google.common.collect.Lists;
public class TwoDimArray {
public static Integer keyCalculator(Pair<Integer, Integer> point) {
return point.getLeft() * point.getRight();
}
public static Map<Integer, Integer> myMethod(List<Pair<Integer, Integer>> points) {
return points.stream()
.collect(Collectors.toMap(p -> keyCalculator(p), p -> p.getRight()));
}
public static void main(String[] args) {
Pair<Integer, Integer> pointA = Pair.of(1, 2);
Pair<Integer, Integer> pointB = Pair.of(3, 4);
Pair<Integer, Integer> pointC = Pair.of(5, 6);
List<Pair<Integer, Integer>> points = Lists.newArrayList(pointA, pointB, pointC);
System.out.println("Points map: " + myMethod(points));
}
}
Which outputs:
Points map: {2=2, 12=4, 30=6}