Java 8: 如何使用流从包含多个HashMap的ArrayList中提取HashMap?

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

Java 8 : how to extract a HashMap from a ArrayList of HashMap in Java 8 using streams?

问题

以下是翻译好的内容:

我在查询数据库时得到了以下样本结果:

dataList = [{ name: name1, rollno: rollno1 }, { name: name2, rollno: rollno2 }]

我想使用Java 8流将这个哈希映射列表转换成一个单独的哈希映射。
我尝试使用Collectors.toMap(),但我不确定如何在toMap方法中引用rollno作为键,以及哈希映射作为值。

预期输出:

{ rollno1: { name: name1, rollno: rollno1 }, rollno2: { name: name2, rollno: rollno2 } }

我尝试使用forEach循环在列表上操作,然后将rollno添加为哈希映射的键,并将哈希映射本身作为该rollno的值。

HashMap<String, HashMap<String, String>> newMap = new HashMap();

for (HashMap<String, String> record : dataList) {
    String key = record.get("rollno").toString();
    newMap.put(key, record);
}

是否有一种方法可以使用Java 8中的函数式流重构这段代码?
在执行此操作时,使用流的collect方法是否会比forEach循环带来性能优势?

非常感谢您的任何指导。谢谢

英文:

I have the following sample result when I query a database :

dataList  = [{ name : name1, rollno: rollno1 }, { name : name2, rollno: rollno2 } ]

I want to convert this list of hashmaps into a single hashmap using Java 8 streams.
I tried using Collectors.toMap() but i am not sure how to refer to rollNo as key and the hashmap as the value inside the toMap method.

Exected output :

{ rollno1 : { name : name1, rollno: rollno1 } , rollno2 : { name : name2, rollno: rollno2 } }

I tried doing it using a for each loop on the list and then adding the rollno as key to a hashmap and the hashmap as value itself of that rollno.


    HashMap&lt;String,HashMap&lt;String,String&gt;&gt; newMap = new HashMap();

    for(HashMap&lt;String,String&gt; record : dataList){
        String key = record.get(&quot;rollno&quot;).toString();
        newMap.put(key,record);
    }

Is there a way to refactor this code using functional streams in Java 8?
Will using streams collect method give any performance advantage over the foreach for doing this?

Will appreciate any leads. Thanks

答案1

得分: 2

因为我不知道您正在使用的对象类型,所以我在字符串上执行这个操作。但对于任何类型的对象都是有效的。

HashMap result = (HashMap<String, HashMap<String, String>>) listOfHashMaps.stream()
               .collect(Collectors.toMap(e-> e.get("roll"),e->e));

由于类型转换将帮助您实现此目标。

英文:

As I don't know the type of Object you are using, so I am performing this on String. But it is valid for any type of object.

 HashMap result = (HashMap&lt;String, HashMap&lt;String, String&gt;&gt;) listOfHashMaps.stream()
               .collect(Collectors.toMap(e-&gt; e.get(&quot;roll&quot;),e-&gt;e));

As type casting will help you to achieve this.

答案2

得分: 2

这里是一个完整的示例,展示如何完成这个操作:

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

public class Main {

    public static void main(String[] args) {
        List<HashMap<String, String>> input = new ArrayList<>();
        HashMap<String, String> subinput1 = new HashMap<>();
        subinput1.put("name", "name1");
        subinput1.put("rollno", "rollno1");
        input.add(subinput1);
        HashMap<String, String> subinput2 = new HashMap<>();
        subinput2.put("name", "name2");
        subinput2.put("rollno", "rollno2");
        input.add(subinput2);
        HashMap<String, HashMap<String, String>> result = input.stream()
                .collect(Collectors.toMap(v -> v.get("rollno"), e -> e));
        System.out.println(result);
    }
}

这段代码遍历了一组HashMap,将其存储在结果HashMap中的指定键中,然后创建了一个Map的Map,其中键是输入映射中的“rollno”,值是输入映射本身。

英文:

Here's complete example how to do it

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

public class Main {

    public static void main(String[] args) {
        List&lt;HashMap&lt;String, String&gt;&gt; input = new ArrayList&lt;&gt;();
        HashMap&lt;String, String&gt; subinput1 = new HashMap&lt;&gt;();
        subinput1.put(&quot;name&quot;, &quot;name1&quot;);
        subinput1.put(&quot;rollno&quot;, &quot;rollno1&quot;);
        input.add(subinput1);
        HashMap&lt;String, String&gt; subinput2 = new HashMap&lt;&gt;();
        subinput2.put(&quot;name&quot;, &quot;name2&quot;);
        subinput2.put(&quot;rollno&quot;, &quot;rollno2&quot;);
        input.add(subinput2);
        HashMap&lt;String, HashMap&lt;String, String&gt;&gt; result = (HashMap&lt;String, HashMap&lt;String, String&gt;&gt;) input.stream()
                .collect(Collectors.toMap(v -&gt; (String) v.get(&quot;rollno&quot;), e -&gt; e));
        System.out.println(result);
    }
}

It iterates over a collection of HashMaps, takes the key in which it should be stored in the result HashMap, then it creates a Map of Maps where the key is the "rollno" from the input map, and value is the input map itself.

答案3

得分: 2

你可以使用Collectors.toMapFunction.identity()如下所示,

list.stream()
    .collect(toMap(e -> e.get("rollno"), Function.identity()));
英文:

You can use Collectors.toMap with Function.identity() as below,

list.stream()
        .collect(toMap(e-&gt;e.get(&quot;rollno&quot;), Function.identity()));

答案4

得分: 1

public static void main(String[] args) {
    List<HashMap<String, String>> input = new ArrayList<>();

    HashMap<String, String> subinput1 = new HashMap<>();
    subinput1.put("name", "name1");
    subinput1.put("rollno", "rollno1");
    input.add(subinput1);

    HashMap<String, String> subinput2 = new HashMap<>();
    subinput2.put("name", "name2");
    subinput2.put("rollno", "rollno2");
    input.add(subinput2);

    //Test key conflict
    HashMap<String, String> subinput3 = new HashMap<>();
    subinput2.put("name", "name3");
    subinput2.put("rollno", "rollno2");
    input.add(subinput2);

    System.out.println("input:" + JSONObject.toJSONString(input));

    HashMap<String, HashMap<String, String>> result = (HashMap<String, HashMap<String, String>>)
        input.stream()
            .collect(Collectors.toMap(
                v -> (String) v.get("rollno"),
                Function.identity(), (oldValue, newValue) -> newValue
            ));
    //fastjson  hashmap-toString use =
    System.out.println(JSONObject.toJSONString(result));
}
英文:
public static void main(String[] args) {
    List&lt;HashMap&lt;String, String&gt;&gt; input = new ArrayList&lt;&gt;();
      
    HashMap&lt;String, String&gt; subinput1 = new HashMap&lt;&gt;();
    subinput1.put(&quot;name&quot;, &quot;name1&quot;);
    subinput1.put(&quot;rollno&quot;, &quot;rollno1&quot;);
    input.add(subinput1);

    HashMap&lt;String, String&gt; subinput2 = new HashMap&lt;&gt;();
    subinput2.put(&quot;name&quot;, &quot;name2&quot;);
    subinput2.put(&quot;rollno&quot;, &quot;rollno2&quot;);
    input.add(subinput2);
      
    //Test key conflict
    HashMap&lt;String, String&gt; subinput3 = new HashMap&lt;&gt;();
    subinput2.put(&quot;name&quot;, &quot;name3&quot;);
    subinput2.put(&quot;rollno&quot;, &quot;rollno2&quot;);
    input.add(subinput2);

    System.out.println(&quot;input:&quot;+ JSONObject.toJSONString(input));

    HashMap&lt;String, HashMap&lt;String, String&gt;&gt; result = (HashMap&lt;String, HashMap&lt;String, String&gt;&gt;) 
       input.stream()
            .collect(Collectors.toMap(
                v -&gt; (String) v.get(&quot;rollno&quot;), 
                Function.identity(),(oldValue, newValue) -&gt; newValue
            ));
    //fastjson  hashmap-toString use =
    System.out.println(JSONObject.toJSONString(result));
}

答案5

得分: 0

可能是这样的:

Map<RollNo, List<Roll>> rollsPerType = rolls.stream()
  .collect(groupingBy(Roll::getRollNo));

其中 Roll 是主要对象,RollNo 是其内部的属性(因为您没有提供实际的定义)。

英文:

Probably something like this:

Map&lt;RollNo, List&lt;Roll&gt;&gt; rollsPerType = rolls.stream()
  .collect(groupingBy(Roll::getRollNo));

where Roll is the main object and RollNo is the property inside (since you didn't provide the actual definitions).

huangapple
  • 本文由 发表于 2020年5月29日 14:22:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/62079838.html
匿名

发表评论

匿名网友

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

确定