Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/341.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java Stream groupingBy:减少到列表的第一个元素_Java_Java 8_Grouping_Java Stream_Collectors - Fatal编程技术网

Java Stream groupingBy:减少到列表的第一个元素

Java Stream groupingBy:减少到列表的第一个元素,java,java-8,grouping,java-stream,collectors,Java,Java 8,Grouping,Java Stream,Collectors,我有一个列表,可以表示(简化)JSON样式: [{codice=EUR,description=EUR,ratio=1},{codice=USD, 描述=美元,比率=1.1}] 我想在地图中转换它,如下所示: {EUR={codice=EUR,description=Euro,ratio=1},USD={codice=USD, 描述=美元,比率=1.1} 我写了一行: getValute().stream().collect(Collectors.groupingBy(Valuta::getCo

我有一个
列表
,可以表示(简化)JSON样式:

[{codice=EUR,description=EUR,ratio=1},{codice=USD, 描述=美元,比率=1.1}]

我想在
地图中转换它,如下所示:

{EUR={codice=EUR,description=Euro,ratio=1},USD={codice=USD, 描述=美元,比率=1.1}

我写了一行:

getValute().stream().collect(Collectors.groupingBy(Valuta::getCodice));
但这会返回一个
映射
,而不是我需要的

我想
mapping()
函数适合我,但不知道如何使用。

您可以使用

Map=list
.stream()
.collect(Collectors.toMap(Valuta::getCodice,v->v));

如果觉得
Function.identity()
更可读,可以将
v->v
替换为
Function.identity()。请注意,默认情况下,
toMap
在遇到重复时将引发异常。

实际上,您需要在此处使用
收集器。toMap
而不是
收集器。groupingBy

Map<String, Valuta> map = 
    getValute().stream()
               .collect(Collectors.toMap(Valuta::getCodice, Function.identity()));
Map=
getValute().stream()
.collect(Collectors.toMap(Valuta::getCodice,Function.identity());
用于基于分组函数对流的元素进行分组。默认情况下,与分组功能具有相同结果的2个流元素将被收集到
列表中


将元素收集到
映射中
,其中键是应用给定键映射器的结果,值是应用值映射器的结果。请注意,
toMap
,默认情况下,如果遇到重复,将抛出异常。

游戏已经有点晚了,请尝试以下操作:

Map<String, Valuta> map = 
    getValute().stream()
               .collect(Collectors.groupingBy(Valuta::getCodice,
                            Collectors.collectingAndThen(
                                Collectors.toList(), 
                                values -> values.get(0))));
Map=
getValute().stream()
.collect(收集器).groupingBy(Valuta::getCodice,
收藏,收藏,然后(
Collectors.toList(),
values->values.get(0));
这里有3种方法

public class Test1 {
  static class Foo {
    public int id, targetCost, actualCost;
    public String ref;

    public Foo(int id, String ref, int actualCost, int targetCost) {

      this.id = id;
      this.targetCost = targetCost;
      this.actualCost = actualCost;
      this.ref = ref;
    }

    public int getId() {
      return id;
    }

    public void setId(int id) {
      this.id = id;
    }

    public int getTargetCost() {
      return targetCost;
    }

    public void setTargetCost(int targetCost) {
      this.targetCost = targetCost;
    }

    public int getActualCost() {
      return actualCost;
    }

    public void setActualCost(int actualCost) {
      this.actualCost = actualCost;
    }

    public String getRef() {
      return ref;
    }

    public void setRef(String ref) {
      this.ref = ref;
    }

    @Override
    public String toString() {
      return " [id=" + id + ", targetCost="
    + targetCost + ", " + "actualCost=" 
          + actualCost + ", ref=" + ref
          + "]";
    }

  }// foo

  public static void main(String[] args) {

    List<Foo> list = Arrays.asList(

        new Foo(1, "P1", 300, 400), new Foo(2, "P2", 600, 400), new Foo(3, "P3", 30, 20),
        new Foo(3, "P3", 70, 20), new Foo(1, "P1", 360, 40), new Foo(4, "P4", 320, 200),
        new Foo(4, "P4", 500, 900)

    );
    // Method 1  : 
    Map<Integer, List<Foo>> collect = list.stream()
        .collect(
            Collectors.groupingBy(
                Foo::getId, 
                Collectors.collectingAndThen(

            Collectors.toList(),

            Function.identity()

        )// andthen

        )// gr

        );
    System.out.println(collect);
    /*
    {
        1=[ [id=1, targetCost=400, actualCost=300, ref=P1],
        id=1, targetCost=40, actualCost=360, ref=P1]],

         2=[ [id=2, targetCost=400, actualCost=600, ref=P2]],

          3=[ [id=3, targetCost=20, actualCost=30, ref=P3], 
           [id=3, targetCost=20, actualCost=70, ref=P3]], 

           4=[ [id=4, targetCost=200, actualCost=320, ref=P4], 
            [id=4, targetCost=900, actualCost=500, ref=P4]]

          }
  */

    // Method 2

    Map<Integer, List<Foo>> collect2 = list.stream().collect(
        Collectors.groupingBy(
            Foo::getId, 
            Collectors.mapping(
                Function.identity(), 
                Collectors.toList())));

    System.out.println(collect2);
    /*
     {
  1=[ [id=1, targetCost=400, actualCost=300, ref=P1], 
   [id=1, targetCost=40, actualCost=360, ref=P1]],

    2=[ [id=2, targetCost=400, actualCost=600, ref=P2]],

     3=[ [id=3, targetCost=20, actualCost=30, ref=P3],
       [id=3, targetCost=20, actualCost=70, ref=P3]],

        4=[ [id=4, targetCost=200, actualCost=320, ref=P4], 
         [id=4, targetCost=900, actualCost=500, ref=P4]]

       }

*/

    // Method 3 

    // If you need to compare something the you can use Compare.comparing

     Map<Integer, List<Foo>> collect3 = list
     .stream()
     .sorted( Comparator.comparing(Foo::getId)
         .thenComparing(Foo::getActualCost)
         .thenComparing(Foo::getTargetCost)    )

     .collect(                 

    Collectors.groupingBy(ch -> ch.id)     



         );

     System.out.println(collect3);


/*
{
  1=[ [id=1, targetCost=400, actualCost=300, ref=P1],  
  [id=1, targetCost=40, actualCost=360, ref=P1]],

   2=[ [id=2, targetCost=400, actualCost=600, ref=P2]],

    3=[ [id=3, targetCost=20, actualCost=30, ref=P3], 
     [id=3, targetCost=20, actualCost=70, ref=P3]],

      4=[ [id=4, targetCost=200, actualCost=320, ref=P4], 
       [id=4, targetCost=900, actualCost=500, ref=P4]]

     }
*/


  }// main

}
公共类Test1{
静态类Foo{
公共int id、目标成本、实际成本;
公共字符串引用;
公共Foo(整数id、字符串引用、整数实际成本、整数目标成本){
this.id=id;
this.targetCost=targetCost;
this.actualCost=actualCost;
this.ref=ref;
}
公共int getId(){
返回id;
}
公共无效集合id(内部id){
this.id=id;
}
public int getTargetCost(){
回报目标成本;
}
公共无效设置目标成本(int targetCost){
this.targetCost=targetCost;
}
public int getActualCost(){
返回实际成本;
}
公共无效设置实际成本(int实际成本){
this.actualCost=actualCost;
}
公共字符串getRef(){
返回ref;
}
公共void setRef(字符串ref){
this.ref=ref;
}
@凌驾
公共字符串toString(){
返回“[id=“+id+”,targetCost=”
+目标成本+”,“+”实际成本=”
+实际成本+”,ref=“+ref
+ "]";
}
}//福
公共静态void main(字符串[]args){
List=Arrays.asList(
新Foo(1,“P1”,300,400),新Foo(2,“P2”,600,400),新Foo(3,“P3”,30,20),
新食品(3,“P3”,70,20),新食品(1,“P1”,360,40),新食品(4,“P4”,320,200),
新富(4,“P4”,500,900)
);
//方法1:
Map collect=list.stream()
.收集(
收集者分组(
Foo::getId,
收藏,收藏,然后(
Collectors.toList(),
Function.identity()
)//然后
)//gr
);
系统输出打印项次(收集);
/*
{
1=[[id=1,targetCost=400,actualCost=300,ref=P1],
id=1,targetCost=40,actualCost=360,ref=P1]],
2=[[id=2,targetCost=400,actualCost=600,ref=P2]],
3=[[id=3,targetCost=20,actualCost=30,ref=P3],
[id=3,targetCost=20,actualCost=70,ref=P3],
4=[[id=4,targetCost=200,actualCost=320,ref=P4],
[id=4,targetCost=900,actualCost=500,ref=P4]]
}
*/
//方法2
Map collect2=list.stream().collect(
收集者分组(
Foo::getId,
图(
Function.identity(),
收藏家;
系统输出打印项次(集合2);
/*
{
1=[[id=1,targetCost=400,actualCost=300,ref=P1],
[id=1,targetCost=40,actualCost=360,ref=P1]],
2=[[id=2,targetCost=400,actualCost=600,ref=P2]],
3=[[id=3,targetCost=20,actualCost=30,ref=P3],
[id=3,targetCost=20,actualCost=70,ref=P3],
4=[[id=4,targetCost=200,actualCost=320,ref=P4],
[id=4,targetCost=900,actualCost=500,ref=P4]]
}
*/
//方法3
//如果你需要比较一些东西,你可以使用compare.comparing
Map collect3=列表
.stream()
.sorted(Comparator.comparing(Foo::getId)
.Then比较(Foo::getActualCost)
.Then比较(Foo::getTargetCost))
.收取(
收集器.分组方式(ch->ch.id)
);
系统输出打印项次(集合3);
/*
{
1=[[id=1,targetCost=400,actualCost=300,ref=P1],
[id=1,targetCost=40,actualCost=360,ref=P1]],
2=[[id=2,targetCost=400,actualCost=600,ref=P2]],
3=[[id=3,targetCost=20,actualCost=30,ref=P3],
[id=3,targetCost=20,actualCost=70,ref=P3],
4=[[id=4,targetCost=200,actualCost=320,ref=P4],
[id=4,targetCost=900,actualCost=500,ref=P4]]
}
*/
}//主要
}

与此问题不完全相关,但与此类似。如果您想按多个参数对列表进行分组,然后需要返回不同类型的对象作为值,则可以尝试此解决方案。 希望对某人有帮助

public Map<Integer, Map<String, ObjectTypeB>> setObjectTypeB(List<ObjectTypeA> typeAList) {

   Map<Integer, Map<String, ObjectTypeB>> map = typeAList.stream()
        .collect(groupingBy(ObjectTypeA::getId,
         groupingBy(ObjectTypeA::getDate, 
         collectingAndThen(mapping(this::getObjectTypeB,toList()),values -> values.get(0)))));    
    return map;
}

    public ObjectTypeB getObjectTypeB(ObjectTypeA typeA) {
       ObjectTypeB typeB = new ObjectTypeB();
       typeB.setUnits(typeA.getUnits());
       return typeB;
}
publicmap setObjectTypeB(列表类型列表){
Map Map=typelist.stream()
.collect(groupingBy)(ObjectTypeA::getId,
public Map<Integer, Map<String, ObjectTypeB>> setObjectTypeB(List<ObjectTypeA> typeAList) {

   Map<Integer, Map<String, ObjectTypeB>> map = typeAList.stream()
        .collect(groupingBy(ObjectTypeA::getId,
         groupingBy(ObjectTypeA::getDate, 
         collectingAndThen(mapping(this::getObjectTypeB,toList()),values -> values.get(0)))));    
    return map;
}

    public ObjectTypeB getObjectTypeB(ObjectTypeA typeA) {
       ObjectTypeB typeB = new ObjectTypeB();
       typeB.setUnits(typeA.getUnits());
       return typeB;
}