代码之家  ›  专栏  ›  技术社区  ›  iam.Carrot

将集合“MyCype”转换为映射<String,设置<Stry> Java流[复制]

  •  1
  • iam.Carrot  · 技术社区  · 5 年前

    我有一个如下的班级:

    public MyClass{
    
        private String propertyOne;
    
        private String propertyTwo;
    
        public String getPropertyOne() {
            return propertyOne;
        }
    
        public String getPropertyTwo() {
            return propertyTwo;
        }
    }
    

    我有一个 Collection<MyClass> 称为数据。

    我想把这个转换成 Map<String, Set<String>> 钥匙在哪里 propertyOne 以及 Set<String> 是一套 propertyTwo

    我不知道该怎么做。下面是我未完成的尝试。

    Map<String, Set<String>> returner = data.stream()
                .collect(Collectors.groupingBy(MyClass::getPropertyOne, Collectors.collectingAndThen(
                        // something here I guess
                )));
    

    我知道我可以在这里为每个循环使用传统的,但我正在寻找一个 JavaStreams 实施。

    2 回复  |  直到 5 年前
        1
  •  0
  •   iam.Carrot    5 年前

    这基本上就是你所做的,但是没有 collectingAndThen

    data.stream()
        .collect(Collectors.groupingBy(
                     MyClass::getPropertyOne, 
                     Collectors.mapping(MyClass::getPropertyTwo, Collectors.toSet())
                 ); 
    
        2
  •  0
  •   Mukesh Katariya    5 年前
    public class MyClass{
    
    private String propertyOne;
    
    private String propertyTwo;
    
    public String getPropertyOne() {
            return propertyOne;
            }
    
    public String getPropertyTwo() {
            return propertyTwo;
            }
    
        public MyClass(String propertyOne, String propertyTwo) {
            this.propertyOne = propertyOne;
            this.propertyTwo = propertyTwo;
        }
    }
    
     public static void main(String args[]){
            List<MyClass> l = new ArrayList<>();
            l.add(new MyClass("1","2"));
            l.add(new MyClass("1","3"));
            l.add(new MyClass("2","5"));
            l.add(new MyClass("2","4"));
    
            Map<String, Set<String>> multimap = l.stream()
                    .collect(Collectors.groupingBy(MyClass::getPropertyOne,
                            Collectors.mapping(MyClass::getPropertyTwo,
                                 Collectors.toSet())));
    
            System.out.println("x1 = " + multimap);
    }
    

    x1=1=[2,3],2=[4,5]