将所有基于相同名称条件的哈希映射在Java 8中合并在一起。

huangapple 未分类评论44阅读模式
英文:

Put all hashmap together based on same name condition in java 8

问题

public class PersonAgg {
    
    public static void main(String[] args) {
        List<Person> persons = new ArrayList<>();
        Map<String, Integer> age = new HashMap<>();
        Map<String, Integer> age2 = new HashMap<>();
        Map<String, Integer> age3 = new HashMap<>();
        Map<String, Integer> age4 = new HashMap<>();
        age.put("One", 1);
        age2.put("Two", 2);
        age3.put("Three", 3);
        age4.put("Four", 4);
        persons.add(new Person("Ajay", age));
        persons.add(new Person("Vijay", age2));
        persons.add(new Person("Ajay", age3));
        persons.add(new Person("Vijay", age4));
        
        List<Map<String, Object>> outputList = new ArrayList<>();
        Map<String, List<Map<String, Object>>> nameMap = new HashMap<>();
        
        for (Person person : persons) {
            Map<String, Object> personMap = new HashMap<>();
            personMap.put("name", person.getName());
            Map<String, Object> hashMapValue = new HashMap<>();
            hashMapValue.put("age", person.getAge());
            personMap.put("HashMapValue", hashMapValue);
            
            List<Map<String, Object>> ageList = nameMap.getOrDefault(person.getName(), new ArrayList<>());
            ageList.add(personMap);
            nameMap.put(person.getName(), ageList);
        }
        
        for (String name : nameMap.keySet()) {
            List<Map<String, Object>> ageList = nameMap.get(name);
            Map<String, Object> aggregatedMap = new HashMap<>();
            for (Map<String, Object> ageMap : ageList) {
                aggregatedMap.putAll(ageMap);
            }
            outputList.add(aggregatedMap);
        }
        
        System.out.println(outputList);
    }
}

class Person {
    
    public Person(String name, Map<String, Integer> age) {
        super();
        this.name = name;
        this.age = age;
    }
    
    private String name;
    private Map<String, Integer> age;

    public String getName() {
        return name;
    }

    public Map<String, Integer> getAge() {
        return age;
    }
}
英文:
public class PersonAgg {
	
	public static void main(String[] args) {
		List&lt;Person&gt; persons = new ArrayList&lt;&gt;();
		Map&lt;String, Integer&gt; age = new HashMap&lt;&gt;();
		Map&lt;String, Integer&gt; age2 = new HashMap&lt;&gt;();
		Map&lt;String, Integer&gt; age3 = new HashMap&lt;&gt;();
		Map&lt;String, Integer&gt; age4 = new HashMap&lt;&gt;();
		age.put(&quot;One&quot;, 1);
		age2.put(&quot;Two&quot;, 2);
		age3.put(&quot;Three&quot;, 3);
		age4.put(&quot;Four&quot;, 4);
		persons.add(new Person(&quot;Ajay&quot;, age));
		persons.add(new Person(&quot;Vijay&quot;, age2));
		persons.add(new Person(&quot;Ajay&quot;, age3));
		persons.add(new Person(&quot;Vijay&quot;, age4));
		
	}

}

class Person {
	
	public Person(String name, Map&lt;String, Integer&gt; age) {
		super();
		this.name = name;
		this.age = age;
	}

	private String name;
	private Map&lt;String, Integer&gt; age;

Now I want output like : {name : Ajay, HashMapValue : {age :[&quot;One&quot;,1],} age3 :[&quot;Three&quot;,3]}, {name : Vijay , HashMapValue : {age2 :[&quot;Two&quot;,2],} age4 :[&quot;Four&quot;,4]}

答案1

得分: 0

可以尝试类似这样的代码:

Map<String, Map<String, Integer>> grouped = persons.stream()
    .collect(toMap(Person::getName, Person::getAge, (p1, p2) -> {
        p1.putAll(p2);
        return p1;
    }));
英文:

You can try something like this:

Map&lt;String, Map&lt;String, Integer&gt;&gt; grouped = persons.stream()
	.collect(toMap(Person::getName, Person::getAge, (p1, p2) -&gt; {
	    p1.putAll(p2);
		return p1;
	}));

答案2

得分: 0

不是完美的所以请随意改进这个答案

public class Test
{
 public static void main(String args[])
 {
  List<Person> persons = List.of(new Person("Ajay", Map.of("One", 1)),
                                  new Person("Vijay", Map.of("Two", 2)),
                                  new Person("Ajay", Map.of("Three", 3)),
                                  new Person("Vijay", Map.of("Four", 4)));
  
  Map<String, List<String>> values =
      persons.stream()
             .collect(Collectors.groupingBy(p -> "name : " + p.name + ", HashMapValue: ",
                                            Collectors.mapping(p2 -> p2.age.entrySet().stream(),
                                                               Collectors.flatMapping(ages -> ages.map(entry -> get(entry)),
                                                                                     Collectors.toList())))
            );
  
  
  System.out.println("{");
  values.entrySet().forEach((value) ->
  {
   System.out.print(value.getKey());
   value.getValue().forEach((age) -> System.out.print(age + ","));
   System.out.println();
  });
  System.out.println("}");
 }
 
 private static String get(Entry<String, Integer> entry)
 {
  String map;
  
  switch(entry.getKey())
  {
   case "One": map = "age";
              break;
   case "Two": map = "age2";
              break;
   case "Three": map = "age3";
                break;
   default: map = "age4";
  }
  
  return map + " :[" + entry.getKey() + "," + entry.getValue() + "]";
 }

 private static class Person
 {
  private final String name;
  private final Map<String, Integer> age;
  
  private Person(String name, Map<String, Integer> age)
  {
   this.name = name;
   this.age = age;
  }
 }
}

Output:

{
 name : Ajay, HashMapValue: age :[One,1],age3 :[Three,3],
 name : Vijay, HashMapValue: age2 :[Two,2],age4 :[Four,4],
}
英文:

Not perfect So please feel free to improve upon this answer

public class Test
{
 public static void main(String args[])
 {
  List&lt;Person&gt; persons=List.of(new Person(&quot;Ajay&quot;,Map.of(&quot;One&quot;,1))
                              ,new Person(&quot;Vijay&quot;,Map.of(&quot;Two&quot;,2))
                              ,new Person(&quot;Ajay&quot;,Map.of(&quot;Three&quot;,3))
                              ,new Person(&quot;Vijay&quot;,Map.of(&quot;Four&quot;,4)));
  
  Map&lt;String,List&lt;String&gt;&gt; values=                     
                               persons.stream()
                              .collect(Collectors.groupingBy(p-&gt;&quot; name : &quot;+p.name+&quot;, HashMapValue: &quot;,
                                       Collectors.mapping(p2-&gt;p2.age.entrySet().stream(),
                                       Collectors.flatMapping(ages-&gt;ages.map(entry-&gt;get(entry))
                                      ,Collectors.toList())))
                                    );
  
  
  System.out.println(&quot;{&quot;);
  values.entrySet().forEach((value)-&gt;
  {
   System.out.print(value.getKey());
   value.getValue().forEach((age)-&gt;System.out.print(age+&quot;,&quot;));
   System.out.println();
  });
  System.out.println(&quot;}&quot;);
 }
 
 private static String get(Entry&lt;String,Integer&gt; entry)
 {
  String map;
  
  switch(entry.getKey())
  {
   case &quot;One&quot;:map=&quot;age&quot;;
   break;
   case &quot;Two&quot;:map=&quot;age2&quot;;
   break;
   case &quot;Three&quot;:map=&quot;age3&quot;;
   break;
   default:map=&quot;age4&quot;;
  }
  
  return map+&quot; :[&quot;+entry.getKey()+&quot;,&quot;+entry.getValue()+&quot;]&quot;;
 }

 private static class Person
 {
  private final String name;
  private final Map&lt;String,Integer&gt; age;
  
  private Person(String name,Map&lt;String,Integer&gt; age)
  {
   this.name=name;
   this.age=age;
  }
 }

Output:

{
 name : Ajay, HashMapValue: age :[One,1],age3 :[Three,3],
 name : Vijay, HashMapValue: age2 :[Two,2],age4 :[Four,4],
}

huangapple
  • 本文由 发表于 2020年4月4日 14:16:31
  • 转载请务必保留本文链接:https://java.coder-hub.com/61024449.html
匿名

发表评论

匿名网友

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

确定