您可以使用IntStream 过滤这两个数组:
// assume that two arrays have the same
// length, or 'booArr' is less than 'arr'
Object[] arr = new Object[]{1, 2.0, -1, 3};
Boolean[] booArr = {true, true, false, true};
Object[] validArr = IntStream
// iterate through array indexes
.range(0, booArr.length)
// filter trues
.filter(i -> booArr[i])
// take values that are true
.mapToObj(i -> arr[i])
// return an array
.toArray();
// output
System.out.println(Arrays.toString(validArr));
// [1, 2.0, 3]
如果你有两个列表,方法是一样的:
// assume that two lists have the same
// length, or 'booList' is less than 'list'
List<Object> list = List.of(1, 2.0, -1, 3);
List<Boolean> booList = List.of(true, true, false, true);
List<Object> validList = IntStream
// iterate through list indexes
.range(0, booList.size())
// filter trues
.filter(booList::get)
// take values that are true
.mapToObj(list::get)
// return a List<Object>
.collect(Collectors.toList());
// output
System.out.println(validList);
// [1, 2.0, 3]
另见:How to sort a character by number of occurrences in a String using a Map?