java intersection of two sets of union and difference comparator java two kinds of Comparable and Comparator comparator

 Even seeking the intersection of a collection:

import java.util.ArrayList;
import java.util.List;
public class TestCollection {
    public static void main(String[] args) {
        List<String> strList = new ArrayList<String>();
        List<String> strList2 = new ArrayList<String>();
        for(int i = 0; i < 10; i ++) {
            strList.add("aaa>>" + i);
            strList2.add("aaa>>" + (10 - i));
        }
         
        //求出交集
        strList2.retainAll(strList);
        System.out.println("交集大小:" + strList2.size());
         
        for(int i = 0; i < strList2.size(); i++) {
            System.out.println(strList2.get(i));
        }       
    }
}

And two sets of requirements set:

import java.util.ArrayList;
import java.util.List;
public class TestCollection {
    public static void main(String[] args) {
        List<String> strList = new ArrayList<String>();
        List<String> strList2 = new ArrayList<String>();
        for(int i = 0; i < 10; i ++) {
            strList.add("aaa>>" + i);
            strList2.add("aaa>>" + (10 - i));
        }
        //求出并集
        strList2.removeAll(strList);
        strList2.addAll(strList);
        System.out.println("并集大小:" + strList2.size());      
         
        for(int i = 0; i < strList2.size(); i++) {
            System.out.println(strList2.get(i));
        }       
    }
}

3. difference-set: A part of the element B does not belong to the composition difference set called

list1.remove(list2);

4 to re-sort and

package twolist;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class ListMapSort {
     /**
   * @param args
   */
  public static void main(String[] args) {
    // TODO 自动生成方法存根
    List<Map<String,Object>> listMap1 = new LinkedList<Map<String,Object>>();
    Map<String,Object> map = new HashMap<String, Object>();
    map.put("date", 20121010);
    listMap1.add(map);
    map = new HashMap<String, Object>();
    map.put("date", 20011213);
    listMap1.add(map);
    listMap1.add(map);
    map = new HashMap<String, Object>();
    map.put("date", 20130502);
    listMap1.add(map);
    System.out.println("原始"+listMap1);
    List<Map<String,Object>> listMap2 = new LinkedList<Map<String,Object>>();
    Set<Map> setMap = new HashSet<Map>();
    for(Map<String,Object> map1 : listMap1){
      if(setMap.add(map1)){
        listMap2.add(map1);
      }
    }
    System.out.println("去重"+listMap2);
    Collections.sort(listMap2, new Comparator<Map<String,Object>>(){
      public int compare(Map<String,Object> o1,Map<String,Object> o2){
        return o1.get("date").toString().compareTo(o2.get("date").toString());
      }
    });
    System.out.println("排序:"+listMap2);
  }
}

Java difference between two kinds of Comparable and Comparator comparator

Usually between objects can be seen in two ways:

First: the address of the object is the same, that is, whether or not reference the same object from. This way you can directly use the "==" to complete.

Second aspect: In a certain angle to compare the properties of the object.

 

For JDK8, there are three ways to achieve the object of comparison:

1, override equals Object class () method;

2, inherited Comparable interface, and implement the compareTo () method;

3, the definition of a single object comparator Comparator inherited from the interface, compare () method.

Due to the use of different sort of way, the specific choice of which method to achieve the object of the comparison will be different.

Comparable and Comparator interface class are compared to known, such as Integer, double basic data types, java can compare them, and for comparing the class, the need to manually define the field compare logic used in the comparison. Comparable can be understood as an internal comparator, and the comparator Comparator is an external, substantially the following wording:

class Apple implements Comparable<Apple>{
    int id;
    double price;

    public Apple(int id, double price) {
        this.id = id;
        this.price = price;
    }
    public int compareTo(Apple o) {
        //return Double.compare(this.getPrice(),o.getPrice());
        if (Math.abs(this.price-o.price)<0.001)
            return 0;
        else
            return (o.price-this.price)>0?1:-1;
    }
    @Override
    public String toString() {
        return "Apple{" +
                "id=" + id +
                ", price=" + price +
                '}';
    }
}
class AESComparator implements Comparator<Apple>{

    public int compare(Apple o1, Apple o2) {
        if (Math.abs(o1.price-o2.price)<0.001)
            return 0;
        else{
            return (o1.price-o2.price)>0?1:-1;
        }
    }
}

Implements the Comparable interface class needs to implement compareTo () method, passing an external parameter for comparison, implements Comparator interface need to implement the method compare () method, passing on the outside of two classes are compared, so that the external method called when you compare.

 

First look Arrays and Collections.sort (list, new MyComparator ()); // sort incoming list and a comparator

Before understanding comparator first look at the Arrays class java.util package. This class mainly provides various methods of operation of the array. The most commonly used several methods:

Of Arrays.toString (T [] Data) // will return a string array 
Arrays.sort (T [] Data) // array specified comparison rules to sort in ascending order, T class needs to implement Comparable interface 
Arrays .sort (T [], comparator <? Super T>) // sort the array specified by comparator ascending order 
Arrays.fill (T [] Data, T val) // each element of the array is assigned the value val

The comparator Comparable <T> Interface

Comparison between two methods to achieve the objects, a first method is to achieve Compatable interface. Comparable interface is java.lang the package. The interface is only one way: 

int the compareTo (T O) // Returns three cases: a negative integer, 0, a positive integer. Respectively, less than, equal to, greater than

When we want to compare the size of two objects, due to the existence of the stack is the address of the object, so I can not compare. So we need to implement the Comparable interface, and override the compareTo method. In fact, String class that implements the Comparable interface, only the compareTo () method.

The comparator Comparator <T> Interface
comparison object that implements the second method is a comparison additional writing tools, the tools need to achieve Comparator interface. Since there Comparable interface can achieve more, why have Comparator interface it? Because Comparable interface will be realized when the class definition of good Comparable's compareTo () method. Suppose I have written a City class, do not want to change the internal structure of the class of change, then we can achieve more by class City write a utility class. Further, a number of different methods of comparison can be achieved by a plurality of tools.

public  class A { 

    public XXXX Fun () {
         // business logic
         // xxxxxxxxxxxxxxxxxxx
         // Sort 
        the Collections.sort (myList, new new MyComparator (configValueList)); 
    } 
    / ** 
    * inner class sorting 
    * configValueList collation 
    * in accordance DtoList a certain field, in accordance with the rules configured to sort configValueList 
    * the configValueList [ "a", "B", "C"] 
    * myList myList.get [0] .getVal () = B, myList.get [. 1]. getVal () = A, myList.get [2] .getVal () = C 
    * then sorted myList.get [0] .getVal () = a, myList.get [1] .getVal () = b, myList. GET [2] .getVal () = C 
    * / 
    class MyComparator the implements Comparator<Dto> {
        private List<String> configValueList;

        public MyComparator(List<String> configValueList) {
            this.configValueList = configValueList;
        }

        @Override
        public int compare(Dto dto1, Dto dto2) {
            if(CollectionUtils.isEmpty(configValueList) || dto1 == null || dto2 == null){
                return 0;
            }
            String val1 = dto1.getVal();
            String val2 = dto2.getVal();
            if(StringUtils.isBlank(val1) || StringUtils.isBlank(val2)){
                return 0;
            }
            int sort1 = configValueList.indexOf(val1);
            int sort2 = configValueList.indexOf(val2);
            if(-1 == sort1 || -1 == sort2){
                return 0;
            }
            return sort1 - sort2;
        }
    }
}

Or so that the internal class

public class TestSorting {

    public static void main(String[] args) {

        List<Developer> listDevs = getDevelopers();

        Collections.sort(listDevs, new Comparator<Developer>() {
            @Override
            public int compare(Developer o1, Developer o2) {
                return o1.getAge() - o2.getAge();
            }
        });

        for (Developer developer : listDevs) {
            System.out.println(developer);
        }
    }

    private static List<Developer> getDevelopers() {

        List<Developer> result = new ArrayList<Developer>();

        result.add(new Developer("mkyong", new BigDecimal("70000"), 33));
        result.add(new Developer("alvin", new BigDecimal("80000"), 20));
        result.add(new Developer("jason", new BigDecimal("100000"), 10));
        result.add(new Developer("iris", new BigDecimal("10000"), 23));

        return result;
    }
}

Use Lamdba sort Java8

public class TestSortingLamdba {

    public static void main(String[] args) {

        List<Developer> listDevs = getDevelopers();

        listDevs.sort((Developer o1, Developer o2) -> o1.getAge() - o2.getAge());
        listDevs.forEach(System.out::println);
        System.out.println("----------------");

        listDevs.sort((o1, o2) -> o1.getName().compareTo(o2.getName()));
        listDevs.forEach(System.out::println);
        System.out.println("----------------");

        listDevs.sort(Comparator.comparing(Developer::getSalary));
        listDevs.forEach(System.out::println);
        System.out.println("----------------");

        listDevs.sort(Comparator.comparing(Developer::getSalary).reversed());
        listDevs.forEach(System.out::println);
    }

    private static List<Developer> getDevelopers() {

        List<Developer> result = new ArrayList<Developer>();

        result.add(new Developer("mkyong", new BigDecimal("70000"), 33));
        result.add(new Developer("alvin", new BigDecimal("80000"), 20));
        result.add(new Developer("jason", new BigDecimal("100000"), 10));
        result.add(new Developer("iris", new BigDecimal("10000"), 23));

        return result;
    }
}

 

Guess you like

Origin www.cnblogs.com/h-c-g/p/11082788.html