两维数组通过 [0] 获取 [1]

huangapple go评论68阅读模式
英文:

Two dimensional array get [1] by [0]

问题

int input = 20835;
int result = Arrays.stream(IDS)
                   .filter(id -> id[0] == input)
                   .findFirst()
                   .orElse(new int[]{0, 0})[1];
英文:

What is the fastest one-line implementation to retrieve the value IDS[n][1] when provided with IDS[n][0] as an input using JDK-14.

I don't want to use for (not a one lined implementation). Ideally seeking how this would be done with more recently added java features or Arrays library maybe.

private static final int[][] IDS =
{
	{ 20835, 21608 },
	{ 21608, 21609 },
	{ 20832, 21602 },
	{ 21602, 21603 },
	{ 20833, 21605 },
	{ 21605, 21606 },
	{ 21625, 21623 },
	{ 21623, 21624 },
	{ 20842, 21620 },
	{ 21620, 21621 }
};

Example 1:

Input: 20835
Output: 21608

答案1

得分: 1

在JDK 11的在线编译器上进行了测试方法GiveMeAName将是您的实现这假设任何传递的参数确实存在否则您将收到异常

import java.util.Arrays;
public class MyClass {

    private static final int[][] IDS =
    {
        { 20835, 21608 },
        { 21608, 21609 },
        { 20832, 21602 },
        { 21602, 21603 },
        { 20833, 21605 },
        { 21605, 21606 },
        { 21625, 21623 },
        { 21623, 21624 },
        { 20842, 21620 },
        { 21620, 21621 }
    };

    public static void main(String args[]) {
      System.out.println(GiveMeAName(20835));
    }

    public static int GiveMeAName(int searchValue) {
        return Arrays.stream(IDS).filter(e -> e[0] == searchValue).map(e -> e[1]).findFirst().getAsInt();
    }
}
英文:

Tested on an online compiler for JDK 11. The method GiveMeAName would be your implementation. This assumes that any passed parameter does indeed exist otherwise you will get an exception.

import java.util.Arrays;
public class MyClass {
    
    private static final int[][] IDS =
    {
        { 20835, 21608 },
        { 21608, 21609 },
        { 20832, 21602 },
        { 21602, 21603 },
        { 20833, 21605 },
        { 21605, 21606 },
        { 21625, 21623 },
        { 21623, 21624 },
        { 20842, 21620 },
        { 21620, 21621 }
    };
    
    public static void main(String args[]) {
      System.out.println(GiveMeAName(20835 ));
    }
    
    public static int GiveMeAName(int searchValue) {
        return Arrays.stream(IDS).filter(e -> e[0] == searchValue).map(e -> e[1]).findFirst().get();
    }
}

huangapple
  • 本文由 发表于 2020年10月8日 01:01:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/64248851.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定