使用Java 8遍历一个对象的Map列表并获取项的长度。

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

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&lt;Map&lt;Integer,String&gt;&gt; l = new ArrayList();
Map&lt;Integer,String&gt; m = new HashMap&lt;&gt;();
m.put(1,&quot;Mark&quot;);
m.put(2,&quot;Matthew&quot;);
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&lt;Map&lt;Integer, String&gt;&gt; l) {
    return l.stream()
            .filter(e -&gt; e.containsKey(param))
            .findFirst()
            .map(e -&gt; e.get(param).length())
            .orElseThrow(() -&gt; new IllegalArgumentException(&quot;Element not found!&quot;));
}

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.

huangapple
  • 本文由 发表于 2020年9月17日 01:54:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/63925510.html
匿名

发表评论

匿名网友

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

确定