immutablelist.of
时间: 2023-11-04 15:04:41 浏览: 100
ImmutableList.of is a method in the Guava library for creating an immutable list. It takes one or more elements as arguments and returns an ImmutableList containing those elements.
For example:
```
ImmutableList<String> fruits = ImmutableList.of("apple", "banana", "orange");
```
This creates an immutable list of strings containing the elements "apple", "banana", and "orange". Once created, the list cannot be modified, making it safe for use in concurrent environments.
Note that you can also use the varargs syntax to pass in an array of elements:
```
String[] veggies = {"carrot", "broccoli", "spinach"};
ImmutableList<String> vegetables = ImmutableList.of(veggies);
```
相关问题
ImmutableList.<LauncherApp>builder()无法调用distinct方法
这是因为在Java中,`ImmutableList`是Google Guava库中的一个不可变列表类型,它并没有提供`distinct()`方法。`distinct()`方法是Java 8中`Stream`接口提供的方法,用于对流中的元素进行去重操作。如果你想对一个`ImmutableList`进行去重操作,你可以先将其转换为Java 8中的`Stream`,然后再调用`distinct()`方法,最后将结果转换回`ImmutableList`。示例代码如下:
```
ImmutableList<LauncherApp> apps = ImmutableList.of(app1, app2, app3);
ImmutableList<LauncherApp> distinctApps = apps.stream().distinct().collect(Collectors.collectingAndThen(Collectors.toList(), ImmutableList::copyOf));
```
List<SortDTO> list = ImmutableList.of( new SortDTO("300"), new SortDTO("50"), new SortDTO("200"), new SortDTO("220")); SortDTO[] array = new SortDTO[list.size()];list.toArray(array); log.info("搜索之前:{}", JSON.toJSONString(array)); Arrays.sort(array, Comparator.comparing(SortDTO::getSortTarget)); log.info("先排序,结果为:{}", JSON.toJSONString(array));int index = Arr ays.binarySearch(array, new SortDTO("200"), Comparator.comparing(SortDTO::getSortTarget));if(ind ex<0){ throw new RuntimeException("没有找到 200");} log.info("搜索结果:{}", JSON.toJSONString(array[index]));解释一下
这段代码主要是对一个 SortDTO 的数组进行排序和查找操作。首先,定义了一个包含四个 SortDTO 对象的不可变列表,并将其转换为数组。然后,使用 Arrays.sort() 方法对该数组进行排序,排序的依据是 SortDTO 对象中的 sortTarget 字段。接着,使用 Arrays.binarySearch() 方法在数组中查找 sortTarget 字段为 "200" 的 SortDTO 对象,如果找到则返回该对象在数组中的索引,否则抛出异常。最后,输出排序后的数组和查找结果。