在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进行基本的数据转换操作。你可以根据需要组合这些操作以满足更复杂的需求。