在Java集合框架中,可以使用Stream API進行數據轉換。以下是一些常見的數據轉換操作:
filter()
方法根據條件過濾集合中的元素。import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class FilterExample {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
List<Integer> evenNumbers = numbers.stream()
.filter(n -> n % 2 == 0)
.collect(Collectors.toList());
System.out.println("Even numbers: " + evenNumbers);
}
}
map()
方法將集合中的每個元素轉換為另一種類型。import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class MapExample {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
List<String> stringNumbers = numbers.stream()
.map(String::valueOf)
.collect(Collectors.toList());
System.out.println("String numbers: " + stringNumbers);
}
}
sorted()
方法對集合中的元素進行排序。import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
public class SortExample {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(5, 3, 1, 4, 2);
List<Integer> sortedNumbers = numbers.stream()
.sorted()
.collect(Collectors.toList());
System.out.println("Sorted numbers: " + sortedNumbers);
}
}
flatMap()
方法將嵌套的集合扁平化為一個集合。import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class FlattenExample {
public static void main(String[] args) {
List<List<Integer>> nestedLists = Arrays.asList(
Arrays.asList(1, 2, 3),
Arrays.asList(4, 5, 6),
Arrays.asList(7, 8, 9)
);
List<Integer> flattenedList = nestedLists.stream()
.flatMap(Collection::stream)
.collect(Collectors.toList());
System.out.println("Flattened list: " + flattenedList);
}
}
limit()
和skip()
方法限制集合中的元素數量。import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class LimitAndSkipExample {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
List<Integer> firstThreeNumbers = numbers.stream()
.limit(3)
.collect(Collectors.toList());
System.out.println("First three numbers: " + firstThreeNumbers);
List<Integer> skippedFourthToSixthNumbers = numbers.stream()
.skip(3)
.limit(3)
.collect(Collectors.toList());
System.out.println("Skipped fourth to sixth numbers: " + skippedFourthToSixthNumbers);
}
}
這些示例展示了如何使用Java集合框架中的Stream API進行基本的數據轉換操作。你可以根據需要組合這些操作以滿足更復雜的需求。