您应该能够通过使用一些更准确地反映您的数据的数据结构来帮助自己。如果您有点数据,请考虑使用Pair
,那么您List
的点数实际上就是这样!
接下来,Map
里面的所有结构Java
都会计算自己的哈希值,你不需要这样做!不过,您将需要计算所需的密钥。从您的代码段中,根本不清楚您为什么想要Hashtable/Map
- 它是一个永远不会读取的局部变量,并且会在方法执行后立即进行垃圾收集。因此,我猜你想退货。如果是这样,您可以这样做:
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));
}
}
哪个输出:
Points map: {2=2, 12=4, 30=6}