java8---List、toMap、数组互转、分组(groupingBy、Collect。。。
java8---List、toMap、数组互转、分组(groupingBy、Collect。。。
{
"code1":{"id":"11","name":"n11"},
"code2":{"id":"12","name":"n12"}
}
Map<String, String> idNoMap        = tItems.stream().Map(TItem::getItemId, TItem::getItemNo, (o, n) -> o, LinkedHashMap::new));
Map<String, SaleSkuVO> skuByItemNoMap = skus.stream().Map(SaleSkuVO::getItemNo, p -> p, (o, n) -> o));
Map<String, SaleSkuVO> skuByItemNoMap = skus.stream().Map(SaleSkuVO::getItemNo+ "_" + SaleSkuVO::getItemName, p -> p, (o, n) -> o)); Map<String, SaleSkuVO> skuByItemNoMap = skus.stream().Map(x-&ItemNo() + "_" + x.getItemName(), p -> p, (o, n) -> o));
Map<String, List<SaleSkuVO>> skuByItemNoMapList = skus.stream().upingBy(SaleSkuVO::getItemNo));
{
"code1":[
{"id":"11","name":"n11","code":"code1"},
{"id":"21","name":"n21","code":"code1"}
],
"code2":[
{"id":"12","name":"n12","code":"code2"},
{"id":"22","name":"n22","code":"code2"}
]
}
// 根据id去重
List<Person> unique =
appleList.stream().collect(
collectingAndThen(
toCollection( () -> new TreeSet<>(comparingLong(Apple::getId)) ),
ArrayList::new
)
);
zacard/2016/03/17/java8-list-to-map/
重复key的情况
代码如下:
public Map<String, Account> getNameAccountMap(List<Account> accounts) {
return accounts.stream().Map(Account::getUsername, Function.identity()));
}
这个⽅法可能报错(java.lang.IllegalStateException: Duplicate key),因为name是有可能重复的。toMap有个重载⽅法,可以传⼊⼀个合并的函数来解决key冲突问题:
public Map<String, Account> getNameAccountMap(List<Account> accounts) {
return accounts.stream().Map(Account::getUsername, Function.identity(), (key1, key2) -> key2));
}
这⾥只是简单的使⽤后者覆盖前者来解决key重复问题。
指定具体收集的map
toMap还有另⼀个重载⽅法,可以指定⼀个Map的具体实现,来收集数据:
public Map<String, Account> getNameAccountMap(List<Account> accounts) {
return accounts.stream().Map(Account::getUsername, Function.identity(), (key1, key2) -> key2, LinkedHashMap::new));
}
TreeMap<String, List<User>> treeMap = userList.stream()
.sorted((o1, o2) -> o1.getAge() - o2.getAge())
.collect(groupingBy(item -> Height, TreeMap::new, toList()));
// lambda优雅取出对象list中某个属性重复的集合数据:
public class Test { //blog.csdn/qq_35902833/article/details/88351470
@Data
@AllArgsConstructor
static class Dog {
String name;
int age;
}
public static List<Dog> dogs = null;
static {
dogs = new ArrayList<Dog>() {
{
add(new Dog("黄⼀", 11));
add(new Dog("黄⼀", 22));
add(new Dog("黄三", 33));
}
};
}
//@SuppressWarnings("AlibabaAvoidManuallyCreateThread")
public static void main(String[] args) {
//        dogs.stream()
//                .flatMap(i-&SonList().stream()) // lambda:  list1.addAll(list2)
//                .Set());
Map<String, Long> collect = dogs.stream().
upingBy(i -> i.getName(), unting()));
System.out.println("-1-->" + String()); //-1-->{黄三=1, 黄⼀=2}
Map<String, List<Dog>> collect1 = dogs.stream()
.
upingBy(Dog::getName));
System.out.println("-2-->" + String());//-2-->{黄三=[test.Dog(name=黄三, age=33)], 黄⼀=[test.Dog(name=黄⼀, age=11), test.Dog(name=黄⼀, age=22)]}
IntSummaryStatistics summaryStatistics3 = dogs.stream().collect(Collectors.summarizingInt(Dog::getAge));
System.out.println("-3-->" + Sum());//-3-->66
Map<String, IntSummaryStatistics> intSummaryStatistics = dogs.stream().
upingBy(i -> i.getName(), Collectors.summarizingInt(Dog::getAge)));
System.out.println("-4-->" + intSummaryStatistics);
//-4-->{黄三=IntSummaryStatistics{count=1, sum=33, min=33, average=33.000000, max=33}, 黄⼀=IntSummaryStatistics{count=2, sum=33, min=11, average=16.500000, max=22}}        System.out.println("-5-->" + ("黄⼀").getSum()); //-5-->33
IntSummaryStatistics collect21 = dogs.stream().collect(Collectors.summarizingInt(Dog::getAge));
Optional.ofNullable(collect21).ifPresent(System.out::println);  //IntSummaryStatistics{count=3, sum=66, min=11, average=22.000000, max=33}
System.out.println("-6-->" + Optional.ofNullable(collect21).get().getSum());  //-6-->66
List<String> collect7 = dogs.stream().
upingBy(i -> i.getName(), unting()))
.entrySet()
.stream()
.map(entry -> {
return "key-->" + Key() + "; val-->" + Value();
})
.List());
System.out.println("-7-->" + collect7);  //-7-->[key-->黄三; val-->1, key-->黄⼀; val-->2]
List<String> collect8 = dogs.stream().
upingBy(i -> i.getName(), unting()))
.entrySet()
.stream()
.filter(entry -> Value() > 1)
.map(entry -> Key())
.List());
System.out.println("-7-->" + collect8); //-7-->[黄⼀]
Consumer<Dog> consumer = (dog) -> System.out.println("-8-->" + Age());
Predicate<Dog> dogPredicate = (dog) -> Age() > 10;
Test.dogs.stream()
.
filter(dogPredicate)
.limit(3)
.forEach(consumer);
//-8-->11
//-8-->22
//-8-->33
}
}
// LIST、MAP、数组互转、分组upingBy
public class CollectionMy {
//出处:www.iteye/blog/bugyun-2433872
public static void main(String[] args) {
List<Person> listEntiyJapan = new ArrayList();
listEntiyJapan.add(new Person(1, "ha1", 10));
listEntiyJapan.add(new Person(2, "ha2", 11));
listEntiyJapan.add(new Person(2, "ha3", 12));
//        String[] arrays = {"hello"," , ","world"};
//
//        System.out.println(arrayToList1(arrays));
//        System.out.println(arrayToList2(arrays));
//        System.out.println(listToArray1(arrayToList2(arrays)));
//        System.out.println(listToArray2(arrayToList2(arrays)));
/
/
//        listToMap1(listEntiyChina);
//        sortList(listEntiyJapan);
//
listToMap4(listEntiyJapan);
Map<String, Integer> mapRepeat = new HashMap<>();
}
//--------------进阶-List转为Map---------------------------------
/**
* Java8 List转为Map
* ID 必须为唯⼀性
*
* @param list
* @return
*/
public static void listToMap1(List<Person> list) {
// list<bean> -> Map<String, String>
//使⽤toMap⽅法的另⼀个变体来处理重复问题,它允许我们指定⼀个合并⽅法。这个合并⽅法允许⽤户他们指定想如何处理多个值关联到同⼀个键的冲突。
//在下⾯展⽰的代码中,我们只是使⽤了新的值,当然你也可以编写⼀个智能的算法来处理冲突。
Map<Integer, Person> mapp = list.stream().Map(Person::getId, p -> p, (oldValue, newValue) -> newValue));
//      Map<Integer, Person> mapp = list.stream().Map(Person::getId, Function.ident
ity(),(oldValue, newValue) -> newValue));
System.out.println("-10-->" + mapp);//-10-->{1=Person(id=1, name=ha1), 2=Person(id=2, name=ha2), 3=Person(id=3, name=ha3)}
//可以通过使⽤toMap⽅法的第三个变体来指定其他的映射实现。这需要你指定将⽤来存储结果的Map和Supplier。
Map<Integer, String> map = list.stream().Map(Person::getId, Person::getName, (oldValue, newValue) -> newValue, LinkedHashMap::new));        Map<Integer, String> map01 = list.stream().Map(item -> Id(), item -> Name(), (oldVal, currVal) -> oldVal + "-" + currVal));        System.out.println("-11-->" + map);              //-12-->{1=ha1, 2=ha2, 3=ha3}
System.out.println("-12-->" + String()); //-13-->{1=ha1, 2=ha2, 3=ha3-ha3}
}
/**
* 分组
* Java8 List转为Map  Person -> Map<Integer, List<Person>>
* 根据年龄排序后,再根据ID重复分组
*
* @param list
* @return
*/
public static Map<Integer, List<Person>> listToMap4(List<Person> list) {
Collections.sort(list, Comparatorparing(Person::getId).thenComparing(Person::getAge));
list.forEach(System.out::println);
Map<Integer, List<Person>> result = list.stream().upingBy(Person::getId));
System.out.println("--4---->" + result);
/
/分组演⽰
//      Map<Person, Long> collect41 = list.stream().upingBy(Function.identity(), unting()));
Map<Person, Long> collect41 = list.stream().upingBy(p -> p, unting()));
System.out.println("--41---->" + collect41);
//1.3根据分组的key值对结果进⾏排序、放进另⼀个map中并输出
Map<Integer, Long> result1 = list.stream().upingBy(Person::getId, unting()));
System.out.println("--42---->" + result1);// {1=1, 2=2}
Map<String, Long> xMap = new HashMap<>();
.forEachOrdered(x -> xMap.Key() + "", x.getValue()));
System.out.println("--43---->" + xMap);// {1=1, 2=2}
Map<Integer, Integer> result3 = list.stream().collect(
);
System.out.println("--44---->" + result3);//{1=10, 2=23}
// 根据id去重  blog.csdn/lu930124/article/details/77595585/
List<Person> unique = list.stream().collect(
collectingAndThen(
toCollection(() -> new TreeSet<Person>(comparingLong(Person::getId))), ArrayList::new
)
)
;
System.out.println("--45---->" + unique);//--45---->[Person(id=1, name=ha1, age=10), Person(id=2, name=ha2, age=11)]
return result;
}
//----------------------------------基础操作--------------
/**
* Java8 数组转为List
*
* @param arrays
qq分组简单
* @return
*/
public static List<String> arrayToList1(String[] arrays) {
List<String> result = Stream.of(arrays).List());
return result;
}
/**
* Java8 List转为数组
*
* @param list
* @return
*/
public static String[] listToArray1(List<String> list) {
String[] result = list.stream().toArray(String[]::new);
Arrays.stream(result).forEach(str -> println(str));
return result;
}
public static void sortList(List<Person> list) {
Collections.sort(list, Comparatorparing(Person::getId).thenComparing(Person::getAge));
list.forEach(System.out::println);
}
public static List<String> arrayToList2(String[] arrays) {
List<String> result = Arrays.asList(arrays);
return result;
}
public static String[] listToArray2(List<String> list) {
String[] result = Array(new String[list.size()]);
return result;
}
}
Set<String> skusByItemNoSet = skus.stream().map(SaleSkuVO::getItemNo).Set()); LinkedHashMap

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。