英文:
Iterate through a List of Map of Objects and get the length of an item using Java 8
问题
我有一个对象映射的列表。我想使用Java 8查找映射中特定项目的长度。
List<Map<Integer, String>> l = new ArrayList();
Map<Integer, String> m = new HashMap<>();
m.put(1, "Mark");
m.put(2, "Matthew");
l.add(m);
public int getLength(int param) {
// 这个方法需要在传入1/2时返回Matthew/Mark的长度
// l.stream()
当调用getLength(2)时,它应该返回7
}
英文:
I have a list of Map of Objects. I wanted to find the length of a particular item in a map using Java 8.
List<Map<Integer,String>> l = new ArrayList();
Map<Integer,String> m = new HashMap<>();
m.put(1,"Mark");
m.put(2,"Matthew");
l.add(m);
public int getLength(int param){
//This Method needs to return the length of Matthew/Mark when being passed 1/2
//l.stream()
when getLength(2) is called it should return 7
}
答案1
得分: 1
以下是翻译好的代码部分:
即使在您的代码中存在一些问题,答案可能如下所示:
public int getLength(String param, List<Map<Integer, String>> l) {
return l.stream()
.filter(e -> e.containsKey(param))
.findFirst()
.map(e -> e.get(param).length())
.orElseThrow(() -> new IllegalArgumentException("元素未找到!"));
}
您需要找到包含键 param
的 Map,我猜您希望获取第一个值,然后可以获取其长度,如果未找到元素,则可以用默认值替换 orElseThrow
。
英文:
Even with some problems in your code, the answer could be as this:
public int getLength(String param, List<Map<Integer, String>> l) {
return l.stream()
.filter(e -> e.containsKey(param))
.findFirst()
.map(e -> e.get(param).length())
.orElseThrow(() -> new IllegalArgumentException("Element not found!"));
}
You have to find the Map which contain the key param
, I guess you are looking to the first value then you can get the length or throw an exception if the element not found, you can replace orElseThrow
with orElse
if you want to return default value.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论