需求
代码
Vote类
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;}@Overridepublic 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<String,Integer> map = new HashMap<>();
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);
});
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);