英文:
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();
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论