3月 012018
 

单个List数据去重

思路:利用HashSet
代码:

        List<String> list = new ArrayList<>();
        list.add("a");
        list.add("b");
        list.add("c");
        list.add("c");
        list.add("c");
        for (String string : list) {
            System.out.println(string);
        }
        System.out.println("=============================");
        //转成set
        List<String> listWithoutDup = new ArrayList<>(new HashSet<>(list));
        for (String str : listWithoutDup) {
            System.out.println(str);
        }

多个List合并,数据去重

java 8 之前

思路:

  1. list1.removeAll(list2)
  2. list1.addAll(list2)
    代码
public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        List<String> list2 = new ArrayList<>();
        list.add("a");
        list.add("b");
        list.add("c");
        list.add("c");
        list2.add("a");
        list2.add("e");
        list2.add("e");
        list2.add("g");
        list2.add("g");
        for (String string : list) {
            System.out.println(string);
        }
         //此处指的是将与list2重复的删除
        list.removeAll(list2);
        //此处指加上list2
        list.addAll(list2);
        System.out.println("=============================");
        for (String string : list) {
            System.out.println(string);
        }
    }

java 8以及更高版本:lambda表达式

List<String> result = Stream.of(Lists.newArrayList("1", "1", "3"), Lists.newArrayList("1", "2"))
  .flatMap(Collection::stream).distinct().collect(Collectors.toList());

代码很优雅,但是要合并的list内元素是对象需要equals和hashcode方法

参考资料:

 


 Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

(required)

(required)