Contents

Java Arraylist/array distinct 方法 / 移除 null 方法

整理網路文章方法小記。

list - Get unique values from ArrayList in Java - Stack Overflow

1
2
3
4
5
List<String> gasList = // create list with duplicates...
Set<String> uniqueGas = new HashSet<String>(gasList);
System.out.println("Unique gas count: " + uniqueGas.size());

uniqueGas.toArray(new String[0]);
1
2
3
4
String[] unique = new HashSet<String>(Arrays.asList(array)).toArray(new String[0]);
and shorter and simpler in java 8:

String[] unique = Arrays.stream(array).distinct().toArray(String[]::new);

java - Array of unique elements? - Stack Overflow

1
int[] noDuplicates = IntStream.of(array).distinct().toArray();

Java 8 stream distinct by multiple fields - HowToDoInJava

移除 null 方法

Java program to remove nulls from a List Container

各種寫法…大神啦!!

Java program to remove nulls from a List Container - GeeksforGeeks
備份圖

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import java.util.*;
  
class GFG {
    public static void main(String[] args)
    {
  
        // Create the list with null values
        List<String> list = new ArrayList<>(
            Arrays.asList("Geeks",
                          null,
                          "forGeeks",
                          null,
                          "A computer portal"));
  
        // Print the list
        System.out.println("Initial List: " + list);
  
        // Removing nulls using List.remove()
        // Repeatedly call remove() till all null are removed
        while (list.remove(null)) {
        }
  
        // Print the list
        System.out.println("Modified List: " + list);
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import com.google.common.base.Predicates;
import com.google.common.collect.Iterables;
import java.util.*;
  
class GFG {
    public static void main(String[] args)
    {
  
        // Create the list with null values
        List<String> list = new ArrayList<>(
            Arrays.asList("Geeks",
                          null,
                          "forGeeks",
                          null,
                          "A computer portal"));
  
        // Print the list
        System.out.println("Initial List: " + list);
  
        // Removing nulls using Guava Iterables
        // using Predicate condition isNull()
        Iterables.removeIf(list, Predicates.isNull());
  
        // Print the list
        System.out.println("Modified List: " + list);
    }
}