如何找到Pricepoint的最低排名

时间:2017-12-20 12:13:28

标签: java-8 maps

任何人都可以指导我如何使用外部地图映射内部地图的结果。我创建了一个带有List持有Id,Pricepoint,Rank的List对象,我已经通过获得每个价格点的最低排名映射到内部地图,现在我想将结果映射到他们的特定ID。感谢

public class Pricepoint {

String id;
String pricepoint;
int rank;

public Pricepoint(String id,String pricepoint,int rank)
{
    this.id = id;
    this.pricepoint = pricepoint;
    this.rank= rank;
}


public String getId() {
    return id;
}

public String getPricepoint() {
    return pricepoint;
}

public int getRank() {
    return rank;
}

public static void main(String[] args)
{
    final Comparator<Pricepoint> comp = (p1, p2) -> Integer.compare( p1.getRank(), p2.getRank());
    List<Pricepoint> p = new LinkedList<>();
    p.add(new Pricepoint("1","PP1",1));
    p.add(new Pricepoint("2", "PP1", 2));
    p.add(new Pricepoint("3","PP2",3));
    p.add(new Pricepoint("4", "PP2", 4));
   Map<String,Map<String,Integer>> map1 =   p.stream()
                       .collect(Collectors.toMap(Pricepoint::getPricepoint,Pricepoint::getRank,Math::min))// I'm struck here

1 个答案:

答案 0 :(得分:1)

如果我没有弄错的话,你似乎想要这样的东西:

Map<String, Map<String, Integer>> map1 = p.stream()
            .collect(Collectors.collectingAndThen(
                    Collectors.groupingBy(
                            Pricepoint::getPricepoint,
                            Collectors.collectingAndThen(
                                    Collectors.minBy(Comparator.comparing(Pricepoint::getRank)),
                                    Optional::get)),
                    (Map<String, Pricepoint> x) -> {
                        return x.entrySet()
                                .stream()
                                .collect(Collectors.groupingBy(
                                        entry -> entry.getValue().getId(),
                                        Collectors.toMap(Entry::getKey, e -> e.getValue().getRank())));
                    }));

    System.out.println(map1);

但这只是非常复杂......我真的希望你真的有一个用例。