public class Zoo { private int id; private String name; public Zoo(int s, String a) { this.id = s; this.name = a; } @Override public String toString() { return "Zoo{" + "id=" + id + ", name='" + name + '\'' + '}'; } public int getId() { return id; } }
ArrayList<Zoo> list = new ArrayList<>(); list.add(new Zoo(3,"C")); list.add(new Zoo(1,"A")); list.add(new Zoo(2,"B")); list.add(new Zoo(2,"D"));
忘掉你那暴力的for循环里写sum+=sum,下面几行代码即可:
// 获取最大值 int max = list.stream().mapToInt(Zoo::getId).max().getAsInt(); // 获取最小值 int min = list.stream().mapToInt(Zoo::getId).min().getAsInt(); // 获取平均值 Double avg = list.stream().mapToInt(Zoo::getId).average().getAsDouble();
// 根据id大小进行排序 Collections.sort(list, (o1,o2) -> o1.getId() - o2.getId()); // 或者 Collections.sort(list, Comparator.comparingInt(Zoo::getId)); // 循环输出 list.forEach(o -> System.out.println(o.toString()));
List<Zoo> result = list.stream().filter(o -> o.getId() % 2 != 0).collect(Collectors.toList()); result.forEach(o -> System.out.println(o.toString()));
List<Integer> idList = list.stream().map(Zoo::getId).collect(Collectors.toList()); System.out.println(idList.toString());
针对某个属性去重,首先要在Zoo类中重写hashCode方法,指定是针对哪个属性做哈希,还要重写equal方法:
public class Zoo { private int id; private String name; public Zoo(int s, String a) { this.id = s; this.name = a; } @Override public String toString() { return "Zoo{" + "id=" + id + ", name='" + name + '\'' + '}'; } public int getId() { return id; } /** 如果要根据id查重,就必须重写hashCode和equals方法 **/ @Override public int hashCode(){ return Objects.hash(id); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Zoo zoo = (Zoo) o; return id == zoo.id; } }
// 针对ID去重 List<Zoo> distinct = list.stream().distinct().collect(Collectors.toList()); // 输出 distinct.forEach(o -> System.out.println(o.toString()));
// 限制返回个数 List<Zoo> limits = list.stream().limit(1).collect(Collectors.toList()); limits.forEach(o-> System.out.println(o.toString()));
// N = 1 List<Zoo> skip = list.stream().skip(1).collect(Collectors.toList()); skip.forEach(o-> System.out.println(o.toString()));
// 删除元素 list.removeIf(o -> o.getId() == 3); System.out.println(list.toString());
// List转Map(key必须唯一) Map<Integer, Zoo> zooMap = distinct.stream().collect(Collectors.toMap(Zoo::getId, o -> o)); System.out.println(zooMap.toString());
Map<Integer, Zoo> collect = list.stream() .distinct() .filter(o -> o.getId() % 2 == 0) .skip(0) .limit(1) .collect(Collectors.toMap(Zoo::getId, o -> o)); System.out.println(collect.toString());
第一步查重,肯定只剩下1 A,2 B ,3 C ; 另外一个重复的2 D被排除掉了。
第二步过滤,1,3为奇数,被过滤掉剩下2
第三步跳跃,skip(0)跳过0条,还是2
第四步限制,limit(1)限制返回1条,还是2
第五步list转map,并且用id作为key, 那返回的map就是 {2, {2,‘B’}}
看下结果对不对: