java-stream流案例

需求

在这里插入图片描述

代码

Vote类

// 1. 定义一个投票类
public class Vote {
    private String name;
    private ArrayList<String> voteList;

    public Vote(String name, ArrayList<String> voteList) {
        this.name = name;
        this.voteList = voteList;
    }

    public String getName() {
        return name;
    }

    public ArrayList<String> getVoteList() {
        return voteList;
    }

    @Override
    public String toString() {
        return "Vote{" +
                "name='" + name + '\'' +
                ", voteList=" + voteList +
                '}';
    }
}

创建一个集合

ArrayList<Vote> votes = new ArrayList<>();

ArrayList<String> list = new ArrayList<>();
list.add("农家乐");
list.add("野外拓展");
Vote vote = new Vote("张全蛋儿",list);
votes.add(vote);

ArrayList<String> list2 = new ArrayList<>();
list2.add("轰趴");
list2.add("野外拓展");
list2.add("健身房");
Vote vote2 = new Vote("李二狗子",list2);
votes.add(vote2);

ArrayList<String> list3 = new ArrayList<>();
list3.add("野外拓展");
Vote vote3 = new Vote("翠花",list3);
votes.add(vote3);

ArrayList<String> list4 = new ArrayList<>();
list4.add("轰趴");
list4.add("健身房");
Vote vote4 = new Vote("小帅",list4);
votes.add(vote4);

ArrayList<String> list5 = new ArrayList<>();
list5.add("农家乐");
Vote vote5 = new Vote("有容",list5);
votes.add(vote5);

stream遍历


// 创建一个Map统计对象
Map<String,Integer> map = new HashMap<>();
// 将votes转换为stream流 获取每个vote的voteList对象
votes.stream().map(Vote::getVoteList).forEach(voteList ->{
    voteList.stream().forEach( voteItem ->{
        if (map.containsKey(voteItem)){
            map.put(voteItem,map.get(voteItem)+1);
        }else {
            map.put(voteItem,1);
        }
    });
});
map.forEach((k,v) ->{
    System.out.println(k + " : " + v);
});


// 获取map集合汇总得票数最多的活动
String maxKey = null;
Map.Entry<String,Integer> maxEntry = null;
ArrayList<Map.Entry<String, Integer>> collect = map.entrySet().stream().sorted(
        (e1, e2) -> e2.getValue().compareTo(e1.getValue())
).collect(Collectors.toCollection(ArrayList::new));

maxEntry = collect.get(0);
maxKey = maxEntry.getKey();
System.out.println("得票数最多的活动是:" + maxEntry.getKey() + " : " + maxEntry.getValue());

// 获取没有投最多票的人
String finalMaxKey = maxKey;
List<Vote> noVoteMax = votes.stream().filter(voteItem -> !voteItem.getVoteList().contains(finalMaxKey)).collect(Collectors.toList());
noVoteMax.forEach(System.out::println);
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值