简体   繁体   English

如何在单个语句中创建新列表并添加值

[英]How to create a new list and add a value in single statement

What I'm trying to achieve is probably quite pointless but I would like to find this out to satisfy my curiosity. 我试图实现的目标可能毫无意义,但我想发现这一点来满足我的好奇心。

I'm trying to create a single efficient statement that would create a new list based on another and add a new value to the end. 我正在尝试创建一个有效的语句,该语句将基于另一个语句创建一个新列表,并在末尾添加一个新值。

I'm new to lambda expressions and I'm not sure what kind of list should I be using for this. 我是lambda表达式的新手,我不确定应该使用哪种列表。

the method would look something like this: 该方法将如下所示:

private List<Integer> conjoin(List<Integer> list, Integer newValue){
    return new ArrayList<Integer>(list).stream()
            .map(value -> list.indexOf(value)==(list.size()-1) ? 
                    Arrays.asList(value, newValue) : 
                    Arrays.asList(value))
            .flatMap(Collection::stream)
            .collect(Collectors.toList());        
}

but more neat and efficient. 但更加整洁和高效。

Or is there a built-in method doing the same that I didn't know about? 还是有内置的方法可以做我不知道的事情?

I love one-liners as much as anyone else, but they come with a cost - namely they're harder to read than being explicit. 我和其他任何人一样都喜欢一线,但它们要付出一定的代价-也就是说,比表述更难阅读。 So lets start with the "normal" way to do what you're describing: 因此,让我们从“正常”的方式开始做您要描述的事情:

ArrayList<E> copy = new ArrayList<>(list);
copy.add(value);
return copy;

It's a few lines, but it's efficient, straight-forward, and easy to read. 虽然只有几行,但它高效,直接且易于阅读。 We want any alternative to be an improvement on this syntax, not simply replacing readability for conciseness. 我们希望对这种语法进行任何改进,而不是为了简明而简单地替换可读性。 If you're trying to decide between the implementation you've posted and the "normal" version, the "normal" version should win hands down. 如果您要在已发布的实现和“正常”版本之间做出选择,则“正常”版本应该会比较有用。


We can try to improve on your solution with Stream.concat() and Stream.of() . 我们可以尝试使用Stream.concat()Stream.of()改进您的解决方案。

return Stream.concat(list.stream(), Stream.of(value))
    .collect(Collectors.toList());

It's technically all one statement now, but we still need to split it over multiple lines to make it readable. 从技术上讲,这只是一条语句,但是我们仍然需要将其分成多行以使其可读。 It's also a lot more boilerplate than the standard implementation. 它也比标准实现要复杂得多。


Instead we can use the builder pattern Guava provides for its Immutable collections : 相反,我们可以使用番石榴为其不可变集合提供的构建器模式:

return new ImmutableList.Builder<E>().addAll(list).add(value).build();

This is more concise, and conveys our intent nicely. 这更加简洁,很好地传达了我们的意图。 This is how I would recommend implementing the behavior you describe (using Guava or by defining your own builder pattern ). 这就是我建议实现您描述的行为的方式(使用Guava或定义自己的构建器模式 )。 Not only does it work for this specific use case, but it scales to any arbitrary combination of values and collections. 它不仅适用于此特定用例,而且可以缩放为值和集合的任意组合。


I think (it's hard to read :) ) your example actually replaces the last value of the list with your new value, rather than adding it to the end. 认为 (很难读:))您的示例实际上新值替换了列表的最后一个值,而不是将其添加到末尾。 If that's what you want, just use List.sublist() to truncate the last element from the list, eg: 如果那是您想要的,只需使用List.sublist()截断列表中的最后一个元素,例如:

list.sublist(0, list.size() - 1)

Use that anywhere I have list above to exclude the last value. 在上面list任何地方都可使用该值排除最后一个值。

One option is using 一种选择是使用

List<Integer> newList = (List<Integer>)ListUtils.union(list1,Arrays.asList(5));

From Apache Commons Collections . 来自Apache Commons Collections I understand that internally this is not "one single statement", but that's such an useful library that chances are a lot of people will have it anyway. 我知道在内部这不是“一个声明”,但这是一个有用的库,无论如何,很可能会有很多人拥有它。


Example

// Your list
ArrayList<Integer> myList = new ArrayList<Integer>();
myList.add(2);

// Create new list with new element
List<Integer> newList = (List<Integer>)ListUtils.union(myList,Arrays.asList(5));

You can try this 你可以试试这个

 private List<Integer> conjoin(List<Integer> list, final Integer newValue){
      ArrayList<Integer> returnlist = new ArrayList<Integer>(list) {{
            add(newValue);
        }};
    return returnlist;
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在单个列表中添加多个值HashMap <Integer, ArrayList<User> &gt; map1 =新的HashMap <Integer, ArrayList<User> &gt;(); - How to add a multiple value in a single list HashMap<Integer, ArrayList<User>> map1 = new HashMap<Integer, ArrayList<User>>(); 如何将值添加到哈希图中单个键的值列表中(Java) - How to add a value to a list of values for a single key in a hashmap (Java) 如何在Java中将新键值添加到现有List Map对象 - How to add new key value to existing List Map object in java HashMap + Lambda。如果为null,如何添加新值<List> - HashMap + Lambda. How to add a new value <List> if is null 如何使用 if 语句为字符串添加值 - How to add value to string with if statement 计算地图 - 将元素添加到现有列表或创建新列表并添加到其中 - Compute map - add element to existing List or create new List and add to it 解析字符串,创建单个字符串,并将其与if语句中的值进行比较? - Parse a string, create single strings and compare them to a value in an if statement? 如何使用 JSqlParser 向 select 语句添加新列 - How to add new column to select statement with JSqlParser 我怎样才能创建一个新的元素/节点,然后向它添加一个新的键和值? - How can I create a new element/node and then add a new key and value to it? 如何使用参数创建FunctionCall语句并添加函数 - How to create FunctionCall statement with arguments and add in function
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM