List去重

来源:互联网 发布:塔人网络 仙境传说任务 编辑:程序博客网 时间:2024/03/28 23:18
package com.rain.io.test;import java.util.ArrayList;import java.util.Comparator;import java.util.List;import java.util.Set;import java.util.TreeSet;/** * List去重. */public class TestTreeSet {public static void main(String[] args) {// 方法一:List<Order> list = new ArrayList<Order>();list.add(new Order("1", "2.0"));list.add(new Order("1", "2.0"));list.add(new Order("1", "2.0"));list.add(new Order("1", "2.0"));Set<Order> set = new TreeSet<Order>();for (Order order : list) {set.add(order);}System.out.println(set.size());// 方法二:Set<Fruit> sss = new TreeSet<Fruit>(new Comparator<Fruit>() {@Overridepublic int compare(Fruit o1, Fruit o2) {return (o1.getOrderId() + o1.getTotalPay()).compareTo(o2.getOrderId() + o2.getTotalPay());}});List<Fruit> fruitList = new ArrayList<Fruit>();fruitList.add(new Fruit("1", "2.1"));fruitList.add(new Fruit("1", "2.2"));fruitList.add(new Fruit("1", "2"));fruitList.add(new Fruit("1", "2"));fruitList.add(new Fruit("1", "2"));for (Fruit fruit : fruitList) {sss.add(fruit);}System.out.println(sss.size());}}class Order implements Comparable<Order> {private String orderId;private String totalPay;public String getOrderId() {return orderId;}public void setOrderId(String orderId) {this.orderId = orderId;}public String getTotalPay() {return totalPay;}public void setTotalPay(String totalPay) {this.totalPay = totalPay;}public Order(String orderId, String totalPay) {super();this.orderId = orderId;this.totalPay = totalPay;}@Overridepublic int compareTo(Order o) {Order obj1 = (Order) o;return obj1.getOrderId().compareTo(orderId);}}class Fruit {private String orderId;private String totalPay;public String getOrderId() {return orderId;}public void setOrderId(String orderId) {this.orderId = orderId;}public String getTotalPay() {return totalPay;}public void setTotalPay(String totalPay) {this.totalPay = totalPay;}public Fruit(String orderId, String totalPay) {super();this.orderId = orderId;this.totalPay = totalPay;}}


原创粉丝点击